Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting pointer to the start of file

Tags:

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)

like image 278
Kyuu Avatar asked Sep 03 '15 03:09

Kyuu


2 Answers

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; } 
like image 178
R Sahu Avatar answered Sep 19 '22 21:09

R Sahu


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.
like image 25
paddy Avatar answered Sep 23 '22 21:09

paddy