fgets() help

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • diroddi

    fgets() help

    I have a fixed length file that I am reading and trying to process. The
    file contains 3 types of records (a,b,c) each has it's own field
    definition for the position on the line. Record type is always held in
    position 2(php 0,1,2), with a length of 1.

    I would like to process each line seperatley, evaluating the record
    type, and then taking the appropriate action. Like so:

    //open the import file
    $import_file = fopen(dirname(_ _FILE__)."/../../data/imports/data.imp",
    "r");

    //make sure we can read it
    if($import_file )
    {
    //loop to read each line
    while (!feof($import_ file))
    {
    //read line and process accordingly
    $line = fgets($import_f ile);
    $record_type = substr($line, 2,1);
    if($record_type =="a")
    {
    //process 'a' types
    }
    elseif(record_t ype=='b')
    {
    //process 'b' types
    }
    elseif(record_t ype=='c')
    {
    //process 'c' types
    }
    }//end loop
    }

    I can read the data just fine, my problem is that all records are being
    treated as 'a' records. Any help would be greatly appreciated.


    Thanks

  • NC

    #2
    Re: fgets() help

    diroddi wrote:[color=blue]
    >
    > I have a fixed length file that I am reading and trying
    > to process. The file contains 3 types of records (a,b,c)
    > each has it's own field definition for the position on
    > the line. Record type is always held in position 2 (php
    > 0,1,2), with a length of 1.[/color]
    ....[color=blue]
    > I can read the data just fine, my problem is that all
    > records are being treated as 'a' records.[/color]

    You omitted "$" in a couple of places:
    [color=blue]
    > if($record_type =="a")[/color]

    The above is a correctly written line.
    [color=blue]
    > elseif(record_t ype=='b')
    > elseif(record_t ype=='c')[/color]

    The two lines above, however, refer to a (probably undefined)
    constant record_type, not to the variable $record_type...

    An unrelated suggestion: your code can be streamlined like
    this:

    if($import_file = fopen(dirname(_ _FILE__) .
    "/../../data/imports/data.imp", "r")) {
    while ($line = fgets($import_f ile)) {
    $record_type = substr($line, 2,1);
    switch ($record_type) {
    case 'a':
    // Process 'a' record
    break;
    case 'b':
    // Process 'b' record
    break;
    case 'c':
    // Process 'c' record
    break;
    }
    } else {
    // Handle file opening error.
    }

    Cheers,
    NC

    Comment

    Working...