【发布时间】:2011-06-22 12:19:53
【问题描述】:
根据命令行参数,我将文件指针设置为指向指定文件或标准输入(用于管道)。然后我将此指针传递给许多不同的函数以从文件中读取。下面是获取文件指针的函数:
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;
}
当它指向标准输入时,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);
}
【问题讨论】:
-
您的示例代码对我来说看起来不错。 (除非文件不存在,但这与您的问题无关)
-
对我来说似乎是正确的。它是什么编译器?您可以尝试在 bar() 函数中打印两个指针(stdin 和 myFile)以检查它们是否相同。
-
@leonbloy:我发现问题实际上出在
fseek()。显然当指针指向标准输入时它不起作用?对此有什么想法吗? (更新问题)
标签: c file pointers stdin piping