的文件指针一起使用

的文件指针一起使用

本文介绍了将 fseek 与指向 stdin 的文件指针一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Depending on command-line arguments, I'm setting a file pointer to point either towards a specified file or stdin (for the purpose of piping). I then pass this pointer around to a number of different functions to read from the file. Here is the function for getting the file pointer:

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
", argv[1]);
    }
    else
        myFile = stdin;
    return myFile;
}

当它指向标准输入时,fseek 似乎不起作用.我的意思是我使用它然后使用 fgetc 并且我得到了意想不到的结果.这是预期的行为吗?如果是,我该如何移动到流中的不同位置?

When it's pointing to stdin, fseek does not seem to work. By that, I mean I use it and then use fgetc and I get unexpected results. Is this expected behavior, and if so, how do I move to different locations in the stream?

例如:

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

推荐答案

是的,fseekstdin 上不起作用是完全正常的——它通常会只能处理磁盘文件,或类似的东西.

Yes, it's perfectly normal that fseek won't work on stdin -- it'll normally only work on a disk file, or something reasonably similar.

虽然这确实是一个 POSIX 问题,但您通常可以使用 if (isatty(fileno(myFile))) 至少很好地了解搜索是否适用于特定文件.在某些情况下,isatty 和/或 fileno 将带有前导下划线(例如,IIRC,Microsoft 的编译器提供的版本会这样做).

Though it's really a POSIX thing, you can typically use if (isatty(fileno(myFile))) to get at least a pretty good idea of whether seeking will work in a particular file. In some cases, isatty and/or fileno will have a leading underscore (e.g., IIRC the versions provided with Microsoft's compilers do).

这篇关于将 fseek 与指向 stdin 的文件指针一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:30