Skip reading header of text file in C

Will C

I am reading in data from a file orderedfile.txt. Sometimes this file has a header of the form:

BEGIN header

       Real Lattice(A)               Lattice parameters(A)    Cell Angles
   2.4675850   0.0000000   0.0000000     a =    2.467585  alpha =   90.000000
   0.0000000  30.0000000   0.0000000     b =   30.000000  beta  =   90.000000
   0.0000000   0.0000000  30.0000000     c =   30.000000  gamma =   90.000000

 1                            ! nspins
25   300   300                ! fine FFT grid along <a,b,c>
END header: data is "<a b c> pot" in units of Hartrees

 1     1     1            0.042580
 1     1     2            0.049331
 1     1     3            0.038605
 1     1     4            0.049181

and sometimes no header is present and the data starts on the first line. My code for reading in the data is shown below. It works when the data starts on line one, but not with the header present. Is there a way to get around this?

int readinputfile() {
   FILE *potential = fopen("orderedfile.txt", "r");
   for (i=0; i<size; i++) {
      fscanf(potential, "%lf %lf %*f  %lf", &x[i], &y[i], &V[i]);
   }
   fclose(potential);
}
Andre Kampling

The following code will use fgets() to read each line. For each line sscanf() is used to scan the string and store it into double variables.
See a running example (with stdin) at ideone.

#include <stdio.h>

int main()
{
   /* maybe the buffer must be greater */
   char lineBuffer[256];
   FILE *potential = fopen("orderedfile.txt", "r");

   /* loop through every line */
   while (fgets(lineBuffer, sizeof(lineBuffer), potential) != NULL)
   {
      double a, b, c;
      /* if there are 3 items matched print them */
      if (3 == sscanf(lineBuffer, "%lf %lf %*f %lf", &a, &b, &c))
      {
         printf("%f %f %f\n", a, b, c);
      }
   }
   fclose(potential);

   return 0;
}

It is working with the header you provided but if in the header a line such as:

 1     1     2            0.049331

would appear then this line would also be read. Another possibility would be to search for the word END header if BEGIN header is present as it is in your given header or use a line count if the number of lines is known.
To search for sub strings the function strstr() could be used.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related