You are here:  » Fixed format text file


Fixed format text file

Submitted by Eydun on Sun, 2010-05-16 19:43 in

Hi.

Does Magic Parser parse fixed format text files?

Submitted by support on Mon, 2010-05-17 09:42

Hi Eydun,

I assume you mean text files with fixed width fields rather than being separated by a known character - i'm afraid not if that's the case...

Cheers,
David.

Submitted by Eydun on Mon, 2010-05-17 10:54

Ok, thanks for the reply.

Submitted by support on Mon, 2010-05-17 11:13

Hi again,

fscanf() should make it relatively easy to parse a fixed format text file.

The printf format specifier (also applies to fscanf) for a fixed width text field is, %xs, where is x is the width of the field, so let's say for example, your fixed format text file has 2 colums of 3 characters followed by 2 columns of 5 characters on each line, the fscanf() code to reach each of those fields into 4 appropriately named variables would be:

  fscanf($handle,"%3s%3s%5s%4s",$field1,$field2,$field3,$field4);

...or a more complete example:

  $handle = fopen("filename.txt","r");
  while(!feof($handle))
  {
    fscanf($handle,"%3s%3s%5s%4s",$field1,$field2,$field3,$field4);
    // process $field1, $field2 etc. here!
  }
  fclose($handle);

(fscanf() reads the file one line at a time)

Hope this helps!
Cheers,
David.

Submitted by Eydun on Mon, 2010-05-17 22:06

Thanks! I will examine fscanf further.