简体   繁体   English

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

[英]C - reading from stdin with a file?

So I have a text file that I'm using in the same directory as my C program and I'm using MinGW as the compiler. 因此,我有一个文本文件,正在使用与C程序相同的目录,并且正在使用MinGW作为编译器。 This is my input: 这是我的输入:

./program "hello" > helloworld.txt

In my program in the main function, I have: 在我的程序的主要功能中,我有:

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

Nothing is printing. 什么都没打印。 The text file definitely has lines in it. 文本文件中肯定有行。 I don't know what's going on. 我不知道这是怎么回事。 This assignment voids the use of fopen() and all that. 此分配使fopen()和所有其他内容的使用无效。 It is getchar() and stdin only. 它仅是getchar()和stdin。

Your command isn't reading from the text file, it's writing to it. 您的命令不是从文本文件读取,而是在写入文本文件。 If you want to read from it, you need to do this: 如果要阅读,则需要执行以下操作:

./program < helloworld.txt

helloworld.txt: helloworld.txt:

this
is a
test

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM