Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fseek with a file pointer that points to stdin

Depending on command-line arguments, I'm setting a file pointer to point either towards a specified file or stdin (for the purpose of piping). I then pass this pointer around to a number of different functions to read from the file. Here is the function for getting the file pointer:

FILE *getFile(int argc, char *argv[]) {
    FILE *myFile = NULL;
    if (argc == 2) {
        myFile = fopen(argv[1], "r");
        if (myFile == NULL)
           fprintf(stderr, "File \"%s\" not found\n", argv[1]);
    }
    else
        myFile = stdin;
    return myFile;
}

When it's pointing to stdin, fseek does not seem to work. By that, I mean I use it and then use fgetc and I get unexpected results. Is this expected behavior, and if so, how do I move to different locations in the stream?

For example:

int main(int argc, char *argv[]) {
    FILE *myFile = getFile(argc, argv); // assume pointer is set to stdin
    int x = fgetc(myFile); // expected result
    int y = fgetc(myFile); // expected result
    int z = fgetc(myFile); // expected result

    int foo = bar(myFile); // unexpected result

    return 0;
}

int bar(FILE *myFile) {
    fseek(myFile, 4, 0);
    return fgetc(myFile);
}
like image 676
Tyler Treat Avatar asked Feb 07 '11 03:02

Tyler Treat


People also ask

Can a file pointer point to Stdin?

You can't write to stdin: it is a read-only stream. It would be the equivalent of writing to your mouse and expecting the user to read the message...

Does Fseek work on Stdin?

When it's pointing to stdin, fseek does not seem to work. By that, I mean I use it and then use fgetc and I get unexpected results.

Does Fseek move the file pointer?

fseek() is used to move file pointer associated with a given file to a specific position. position defines the point with respect to which the file pointer needs to be moved.

What is a valid way to call Fseek for a file pointer FP?

Answer: The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at desired location.


1 Answers

Here is the relevant entry in the ANSI standard concerning the fseek function:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET

So, possible but with some limitations

like image 156
Jorge Avatar answered Sep 29 '22 05:09

Jorge