ftell( stdin ) causes illegal seek error

对着背影说爱祢 提交于 2019-12-19 02:45:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2502489/ftell-stdin-causes-illegal-seek-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!