c - 为什么 ftell( stdin ) 导致非法查找错误

标签 c file-io ftell

以下代码输出“非法搜索”:

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

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

当我运行 cat script | 时会发生这种情况./a.out 以及当我刚刚运行 ./a.out 时。当然,问题出在 ftell 上。我的问题是:为什么会发生这种情况?我认为 stdin 是可搜索的。 fseek 也会导致同样的错误。如果 stdin 不可搜索,有什么方法可以做同样的事情吗?

感谢您的回复。

最佳答案

Fifos 不可搜索。它们只是一个缓冲区。一旦数据从 fifo 缓冲区被read(),就永远无法检索到。

请注意,如果您运行程序:

./a.out < script

那么标准输入将是一个文件,而不是一个fifo,所以ftell() 将执行您期望的操作。

关于c - 为什么 ftell( stdin ) 导致非法查找错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2502489/

相关文章:

c - openssl 编译错误

php - php 函数中 ftell 的输出

c - fgetpos() 和 fsetpos() 是否仅适用于文本模式?如果不是字节数,fpos_t 对象填充了哪些位置/偏移数据?

winapi - 快速访问大文件 - fseek ftell fsetpos fgetpos

python - 在 python 中读取大文本文件会随着迭代变慢

perl - 为什么我的用于打印行号前缀的行的 Perl 脚本不起作用?

python - 用C从Chrome中解密 "Saved Password"

c - 警告 : declaration of `lr_searchReplace' does not match previous declaration at vuser_init. c (941)

c - 如何在具有动态字符串的函数中使用 malloc 并且不在末尾添加符号

c - 程序从键盘读取数据,将其写入文件,然后再次从文件读取相同的数据并将其复制到另一个文件并显示?