1

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.

1
  • Your question is misphrased. (1) write "its", not "it's". (2) fscanf() is used to read from a file, not to open a file. You should clarify whether you are reading from stdin or from a file that you fopen()'d. (3) The claim that only one of fscanf() and fgetc() "runs" is gibberish. Do you mean that all of the data from the file had been consumed? Note, alternatives to using fseek() are (a) fopen() the file on multiple handles, or (b) rewind() the file. Commented Sep 6, 2011 at 1:12

1 Answer 1

4

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);

e.g.

  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;
  }
Sign up to request clarification or add additional context in comments.

2 Comments

That should be SEEK_SET, not SEEK_CUR. Seeiking to 0 from CUR won't move the file pointer at all...
Thanks, I'm rusty from java!.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.