【问题标题】:C - reading from stdin with a file?C - 从标准输入读取文件?
【发布时间】:2015-09-17 00:25:08
【问题描述】:

所以我有一个文本文件,我在与我的 C 程序相同的目录中使用它,并且我使用 MinGW 作为编译器。这是我的输入:

./program "hello" > helloworld.txt

在我的程序主函数中,我有:

#include <stdio.h>
int main(int argc, char *argv[]) {
char c;
while ((c=getchar()) != EOF) {
printf("test\n");
}
return 0;
}

什么都没有打印。文本文件中肯定有行。我不知道发生了什么事。此分配使 fopen() 和所有这些的使用无效。它只是 getchar() 和 stdin。

【问题讨论】:

    标签: c file shell stdin getchar


    【解决方案1】:

    您的命令不是从文本文件中读取,而是在写入。如果你想从中读取,你需要这样做:

    ./program < helloworld.txt
    

    helloworld.txt:

    this
    is a
    test
    

    输出:

    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    test
    

    【讨论】:

    • 对不起。那是打错字了。正确的输入有'
    • @Laefica 如果您使用的是&lt;,它应该可以工作。查看我的编辑。
    • 是的,它有效。我真笨。很高兴这个问题将作为那些将来混淆的人的参考,尽管xD
    最近更新 更多