C - 使用文件从标准输入读取?

标签 c file shell stdin getchar

所以我有一个文本文件,它与我的 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。

最佳答案

您的命令不是从文本文件中读取,而是向其中写入。如果您想从中读取内容,您需要执行以下操作:

./program < helloworld.txt

helloworld.txt:

this
is a
test

输出:

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

关于C - 使用文件从标准输入读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32620783/

相关文章:

将静态内核驱动程序编译为模块

c - printf %p 段错误

file - 使用 r+ 模式打开文件时如何删除文件内容?

c - '没有这样的文件或目录。'但文件在那里

sql - 无法在 shell 命令中工作的情况

php - 无法在PHP页面创建的shell脚本中执行sqlplus命令

linux - awk 中的用户定义变量

c - 数组和指针不同

c - 中点集成优化

java - 从方法读取文件时出现无限循环