31

How would I be able to reset a pointer to the start of a commandline input or file. For example my function is reading in a line from a file and prints it out using getchar()

    while((c=getchar())!=EOF)
    {
        key[i++]=c;
        if(c == '\n' )
        {
            key[i-1] = '\0'
            printf("%s",key);
        }       
    }

After running this, the pointer is pointing to EOF im assuming? How would I get it to point to the start of the file again/or even re read the input file

im entering it as (./function < inputs.txt)

Kyuu
  • 953
  • 6
  • 15
  • 25
  • 1
    Just close and reopen the file – asdf Sep 03 '15 at 03:53
  • `EOF ` should be through `stdin` so what are you trying to reset .. If you were getting input from file then `rewind(fp)` would have worked – Gopi Sep 03 '15 at 03:57

2 Answers2

63

If you have a FILE* other than stdin, you can use:

rewind(fptr);

or

fseek(fptr, 0, SEEK_SET);

to reset the pointer to the start of the file.

You cannot do that for stdin.

If you need to be able to reset the pointer, pass the file as an argument to the program and use fopen to open the file and read its contents.

int main(int argc, char** argv)
{
   int c;
   FILE* fptr;

   if ( argc < 2 )
   {
      fprintf(stderr, "Usage: program filename\n");
      return EXIT_FAILURE;
   }

   fptr = fopen(argv[1], "r");
   if ( fptr == NULL )
   {
      fprintf(stderr, "Unable to open file %s\n", argv[1]);
      return EXIT_FAILURE;
   }

    while((c=fgetc(fptr))!=EOF)
    {
       // Process the input
       // ....
    }

    // Move the file pointer to the start.
    fseek(fptr, 0, SEEK_SET);

    // Read the contents of the file again.
    // ...

    fclose(fptr);

    return EXIT_SUCCESS;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 5
    Consider using fseek over rewind, since only fseek provides a return code for error checking: https://www.geeksforgeeks.org/g-fact-82/ – Bl00dh0und Apr 03 '18 at 08:03
  • 'fseek(fptr, 0, SEEK_SET);' worked for me on stdin. Is it unreliable or why did you say it doesn't work on stdin? – daniswhoiam Jan 12 '23 at 13:34
  • @daniswhoiam, I am going to guess that your platform provides functionality that is not guaranteed by the standard. `rewind` is equivalent to `std::fseek(stream, 0, SEEK_SET)`. The [documentation for `fseek`](https://en.cppreference.com/w/cpp/io/c/fseek) indicates that a file stream is expected for `fseek` to work. – R Sahu Feb 13 '23 at 22:56
5

Piped / redirected input doesn't work like that. Your options are:

  • Read the input into an internal buffer (which you already seem to be doing); or
  • Pass the file name as a command-line argument instead, and do with it as you please.
slm
  • 15,396
  • 12
  • 109
  • 124
paddy
  • 60,864
  • 6
  • 61
  • 103