【问题标题】:C: Program asking for user input even when input file is given as an argumentC:即使输入文件作为参数给出,程序也会要求用户输入
【发布时间】:2019-04-11 02:22:08
【问题描述】:

我的程序需要接受一个文件输入,如果没有给出,它需要考虑用户输入作为它的输入。

当我像这样将输入文件输入程序时:

./sim < ex1_in

一切正常!

但是,当我将输入文件指定为文件参数时,如下所示:

./sim ex1_in

程序改为寻找用户输入。

这是处理输入和文件参数的代码部分:

int main(int argc, char * argv []) {    

    if (argc > 3) {
        fprintf (stderr, "Error: Too many arguments.\n");
        return 1;
    }

    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* check file */
        fprintf (stderr, "Error: File Open Failed '%s'.\n", argv[1]);
        return 2;
    }    

    //Initializing array of 256 unsigned chars
    unsigned char binary[256]; 
    int i = 0; 
    unsigned char c;
    int count2 = 0; 


    //populate the 256 byte char array from stdin
    while (count2 < SIZE) {
        c=getchar();
        binary[i] = c;
        i++;
        count2++;                   
    }          

到目前为止,我已将此while 循环确定为问题区域,因为当我将其注释掉时,不会发生不需要的行为。但我不确定为什么会这样。

稍后在main方法中,文件被关闭:

if (fp != stdin) fclose (fp);   /* close file if not stdin */    

另一个相关的事情:

#define SIZE 256

【问题讨论】:

  • fopen,但我不认为 getchar 知道你的 fp 指针。其他功能会更好。
  • 你应该在binary的声明中使用SIZE宏。

标签: c command-line-arguments stdin fopen


【解决方案1】:

getchar()stdin 读取,但您必须从fp 完成所有输入。将getchar() 更改为getc(fp)

getchar() 基本上只是getc(stdin) 的缩写。

另一种方法是将stdin 连接到文件,而不是使用其他变量。

if (argc > 1) {
    freopen(argv[1], "r", stdin);
}

【讨论】:

  • 如果需要,也许检查 argc 并分配 fp 标准输入。
  • 解决了,谢谢!我想知道这是否是我需要做的,但我觉得 ...fopen (argv[1], "r") : stdin;意味着我不需要这样做。
  • 你为什么会这样想?程序可以打开文件并仍然从标准输入读取。
  • @MichaelDorgan 我在您发表评论时将其添加到答案中。
  • 如果使用第二种方法,则没有fp。你只是像往常一样阅读stdin
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多