简体   繁体   中英

Once a file is opened using fscanf() can I read it again?

I need to open a text document and read it's data. One of the data points in this file is an int that I need to use to create a data structure.

Question: Once I open a file passed in from the command line with fscanf() can I read the file again with fscanf() or another stream reading function? I have tried do this by calling fscanf() then fgetc() but I find that the one I call first is the only one that runs.

In order to re-read all or a portion of an opened file, you need to reposition the stream.

You can use fseek() to reposition the file stream to the beginning (or other desired position):

int fseek(FILE *stream_pointer, long offset, int origin);

eg

  FILE *file_handle;
  long int file_length;

  file_handle = fopen("file.bin","rb");
  if (fseek(file_handle, 0, SEEK_SET)) 
  {
    puts("Error seeking to start of file");
    return 1;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM