根据命令行参数,我设置一个文件指针指向指定文件或标准输入(用于管道传输)。然后,我将此指针传递给许多不同的函数以从文件中读取。这是获取文件指针的函数:
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;
}
当它指向 stdin 时,fseek
似乎不起作用。我的意思是我使用它然后使用fgetc
我得到了意想不到的结果。这是预期的行为吗?如果是,我如何移动到流中的不同位置?
例如:
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);
}
是的,这是完全正常的fseek
不起作用stdin
——它通常只适用于磁盘文件或相当类似的文件。
虽然这确实是 POSIX 的东西,但你通常可以使用if (isatty(fileno(myFile)))
至少可以很好地了解查找是否适用于特定文件。在某些情况下,isatty
and/or fileno
将有一个前导下划线(例如,IIRC 是随 Microsoft 编译器提供的版本)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)