ant2009
ant2009

Reputation: 22696

file pointer and using fgets

gcc 4.4.4 c89

I am reading in a file and in that file I have to do some operation on each line.

In a loop I call a 2 functions that pass in this file pointer to perform 2 different operations on the file.

However, as I am using fgets to read in a line of that text file. It automatically increments to the next line. So for the second call, it has already incremented. However, I want to perform a different operation on the same line as the first function.

FILE *fp = NULL;
fp = fopen("devices.txt", "r");
for each line
    get_devicename(fp); <-- calls fgets and operates on line 1, then increments to line 2

    get_machine_code(fp); <-- calls gets and already on line 2, I need line 1
end for

To have a work around, I created 2 file pointers objects and passed them to the functions. However, in the future I might need more operations to do on this text file. So not very scalable if I have to keep creating instances of the file pointer.

Many thanks for any suggestions,

Upvotes: 3

Views: 10781

Answers (3)

Gerhard
Gerhard

Reputation: 7069

C files provide two function sets that can do this for you. Use ftell to get the current position and fseek to go back to that position. see code:

#include <stdio.h>

int main ()
{
  FILE * pFile;
  int pos;

  pFile = fopen("devices.txt", "r");
  pos = ftell (pFile);
  fgets(buf,sizeof(buf),pFile );
  fseek ( pFile , pos , SEEK_SET );
  fgets(buf,sizeof(buf),pFile);
  return 0;
}

And the second option is fgetpos and fsetpos. See code:

#include <stdio.h>

int main ()
{
  FILE * pFile;
  fpos_t position;

  pFile = fopen ("myfile.txt","w");
  fgetpos (pFile, &position);
  fputs ("That is a sample",pFile);
  fsetpos (pFile, &position);
  fputs ("This",pFile);
  fclose (pFile);
  return 0;
}

But I would rather just read once and then pass your file content to two functions instead of reading twice. I can't think of any reason to read the same data twice.

Upvotes: 2

nos
nos

Reputation: 229342

Read the line first, then pass that line to your get_XXX functions:

FILE *fp = NULL;
char buf[4096];
fp = fopen("devices.txt", "r");
while(fgets(buf,sizeof buf,fp) != NULL) {
    get_devicename(buf);
    get_machine_code(buf);
}

Upvotes: 8

mmmmmm
mmmmmm

Reputation: 32720

Better to get the line as a string and then then call functions to get data using this string rather than pass the file pointer around

Upvotes: 2

Related Questions