Search code examples
cfseek

In file reading, how to skip the Nth first lines


I have written a program to read the X, Y and Z coordinates of a molecule from a file (input.xyz) and do some task. However, I want my program to skip the first two lines as my input file has the following structure:

3 
water 
O      -0.73692879      -1.68212007      -0.00000000 
H       0.03427635      -1.68212007      -0.59075946 
H      -1.50813393      -1.68212007      -0.59075946

I have used the following section in my code

fptr = fopen(filename, "r");
fseek(fptr,3,SEEK_SET);
for(i=0;i<Atom_num;i++)
{
   X[i] = Y[i] = Z[i] = 0;
   fscanf(fptr,"%2s%lf%lf%lf",Atom[i].symbol,&X[i],&Y[i],&Z[i]);
   printf("%2s\t%lf\t%lf\t%lf\n",Atom[i].symbol,X[i],Y[i],Z[i]);
}
fclose(fptr);

Where Atom_num is the first line of input.xyz

However, printf shows the following output

at  0.000000    0.000000    0.000000 
er  0.000000    0.000000    0.000000  
O   -0.736929   -1.682120   -0.000000

I do not know why fseek() is not working. Can anyone help me with this?


Solution

  • Look at the signature of fseek():

    int fseek(FILE *stream, long int offset, int whence)
    

    especially at the definition of offset

    offset − This is the number of bytes to offset from whence.

    So when you do:

    fseek(fptr,3,SEEK_SET);
    

    you just skip 3 bytes in the input file.

    What you want to do is something like this:

    char line[256]; /* or other suitable maximum line size */
    while (fgets(line, sizeof line, file) != NULL) /* read a line */
    {
        if (count == lineNumber)
        {
            //Your code regarding this line and on, 
              or maybe just exit this while loop and 
              continue reading the file from this point.
        }
        else
        {
            count++;
        }
    }