12

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

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);
}
4

3 回答 3

14

是的,fseek无法正常工作是完全正常的stdin——它通常只能在磁盘文件或类似的东西上工作。

虽然它确实是一个 POSIX 的东西,但您通常可以if (isatty(fileno(myFile)))用来至少很好地了解搜索是否可以在特定文件中工作。在某些情况下,isatty和/或fileno会有一个前导下划线(例如,微软编译器提供的版本的 IIRC)。

于 2011-02-07T03:27:00.127 回答
2

Fseek() 基于 lseek(),lseek 手册页讨论了可能的错误,包括:

 [ESPIPE]           Fildes is associated with a pipe, socket, or FIFO.

如果 stdin 连接到伪 tty,我相信它会有套接字行为。

于 2011-02-07T03:28:07.867 回答
1

以下是 ANSI 标准中有关该fseek功能的相关条目:

对于文本流,偏移量应为零,或偏移量应为先前成功调用与同一文件关联的流上的 ftell 函数返回的值,并且应为 SEEK_SET

所以,可能,但有一些限制

于 2019-03-31T22:23:52.643 回答