相关疑难解决方法(0)

使用带有指向stdin的文件指针的fseek

根据命令行参数,我设置一个文件指针指向指定文件或stdin(用于管道).然后我将这个指针传递给许多不同的函数来从文件中读取.这是获取文件指针的函数:

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;
}
Run Code Online (Sandbox Code Playgroud)

当它指向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); …
Run Code Online (Sandbox Code Playgroud)

c stdin pointers file piping

10
推荐指数
1
解决办法
1万
查看次数

标签 统计

c ×1

file ×1

piping ×1

pointers ×1

stdin ×1