使用fseek的使用指向标准输入文件指针 [英] Using fseek with a file pointer that points to stdin

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

问题描述

根据命令行参数,我设置一个文件指针指向可能朝向一个指定的文件或标准输入(管道的目的)。然后我周围通过这个指针的若干不同的功能从文件中读取。下面是函数得到该文件指针:

  FILE *的GetFile(INT ARGC,CHAR *的argv []){
    FILE * MYFILE = NULL;
    如果(的argc == 2){
        MYFILE = FOPEN(的argv [1],R);
        如果(MYFILE == NULL)
           fprintf中(标准错误,文件\\%s \\的没有找到\\ n,ARGV [1]);
    }
    其他
        MYFILE =标准输入;
    返回MyFile的;
}

当它指向标准输入, fseek的似乎并没有工作。到那个,我的意思是我用它,然后使用龟etc ,我得到意想不到的效果。这是预期的行为,如果是这样,我怎么移动到其他位置的流?

例如:

  INT主(INT ARGC,CHAR *的argv []){
    FILE * MYFILE =的GetFile(ARGC,ARGV); //假设指针设置为标准输入
    INT X =龟etc(MYFILE); // 预期结果
    INT Y =龟etc(MYFILE); // 预期结果
    INT Z =龟etc(MYFILE); // 预期结果    INT富=栏(MYFILE); //意外的结果    返回0;
}INT栏(FILE * MYFILE){
    fseek的(MYFILE,4,0);
    返回龟etc(MYFILE);
}


解决方案

是的,这是完全正常的, fseek的将无法在标准输入<工作/ code> - 这将通常只对一个磁盘文件的工作,或者说合理类似

虽然这真是一个POSIX的事情,你通常可以使用如果(isatty(的fileno(MYFILE)))来获得至少pretty是否好主意寻求将在一个特定的文件工作。在某些情况下, isatty 和/或的fileno 将有一个前导下划线(例如,IIRC提供了与微软的编译器版本这样做)。

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

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?

For example:

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

解决方案

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.

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的使用指向标准输入文件指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆