Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why ftell( stdin ) causes illegal seek error

Tags:

c

file-io

ftell

The following code outputs "Illegal seek":

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    errno = 0;
    getchar();
    getchar();
    getchar();
    ftell( stdin );
    printf( "%s\n", strerror(errno) );
}

This occurs when I run cat script | ./a.out as well as when I just run ./a.out. The problem is with ftell, of course. My question is: why does this occur? I would think stdin can be seekable. fseek also causes the same error. If stdin is not seekable, is there some way I can do the same sort of thing?

Thank you for your replies.

like image 690
Jim Avatar asked Mar 23 '10 18:03

Jim


1 Answers

Fifos aren't seekable. They are simply a buffer. Once data has been read() from a fifo buffer, it can never be retrieved.

Note that if you ran your program:

./a.out < script

then standard input would be a file and not a fifo, so ftell() will then do what you expect.

like image 116
geocar Avatar answered Oct 02 '22 20:10

geocar