重定向标准输入-C [英] Redirecting stdin - C
本文介绍了重定向标准输入-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我打算通过执行以下命令来接受文本文件:
So I'm meant to accept a text file by doing the following command:
$ sort < list.txt
我知道列表文本文件已输入到我的排序程序中,但是实际上我该如何使用程序中的信息?我怎么读?
I understand that the list text file is being inputted to my sort program, but how do I actually use the information inside my program? How do I read it?
我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char c;
while (c != EOF){
c = getchar();
printf("%c ",c);
}
return (0);
}
示例:
$ ./sort.c < input.txt
./sort.c: line 3: $'\r': command not found
./sort.c: line 4: syntax error near unexpected token `('
'/sort.c: line 4: `int main(int argc, char** argv) {
推荐答案
当您在帖子中编写时,在命令行上使用"<
"符号时,操作系统将读取文件并通过 stdin
将内容提供给您的程序.因此,您所需要做的就是阅读stdin.
When you use the '<
' symbol on the command line as you have written in your post, the OS reads the file for you and gives the contents to your program via stdin
. So, all you need to do is to read from stdin.
这是一个非常简单的代码段来演示-
Here is a very simple code snippet to demonstrate -
#include <stdio.h>
int main() {
char line[256];
FILE *fp = stdin;
while(fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
}
这篇关于重定向标准输入-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文