Reset pointer to start of file

How could I reset the pointer to the beginning of the input or command line file. For example, my function reads a line from a file and prints it using getchar ()

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

After starting, the pointer points to EOF im suggesting? How can I make it point to the beginning of the file again / or even re-read the input file

im introduces it like (./function <inputs.txt)

+12
source share
2 answers

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

 rewind(fptr); 

or

 fseek(fptr, 0, SEEK_SET); 

to reset pointer to the beginning of the file.

You cannot do this for stdin .

If you need 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; } 
+25
source

Channel / redirected input does not work like that. Your options:

  • Read the input into the internal buffer (which you seem to be already doing); or
  • Instead, pass the file name as an argument to the command line and do it as you wish.
+4
source

All Articles