根据命令行参数,我将文件指针设置为指向指定文件或标准输入(用于管道)。然后我将此指针传递给许多不同的函数以从文件中读取。这是获取文件指针的函数:
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);
}