问题描述
我是编码的初学者,C是我一直在学习的唯一语言.我已经对输入重定向到文件进行了深入的研究,以试图弄清楚它是如何工作的,但是我不知道在哪里使用命令或确切地如何使用它.我的问题是,我应该在哪里将重定向命令行准确地放在程序中?我知道它看起来像这样:./a< filename.txt,但是我不知道将其放在程序中的什么位置,或者甚至将其放入程序中?我想使用一个简单的循环将文件中的数据读取到scanf中.另外,"a"是您正在编写的C程序的确切名称吗?
I'm very beginner-level in coding, C is the only language I have been learning. I've done thorough research on input redirection to a file to try to figure out how it works, but I do not understand where to use the command or exactly how it is used. My question is, where do I put the redirection command line in the program exactly? I know that it looks something like this: ./a < filename.txt , but I have no idea where to put it in the program, or if it even goes in the program? I want to read data from the files into a scanf using a simple loop. Also, the 'a', is that the exact name of the C program you are writing?
推荐答案
如果要从重定向中读取,则程序需要从中读取stdin
:
If you want to read from a redirection, then the program needs to read fromstdin
:
int main(void)
{
char line[1024];
fgets(line, sizeof line, stdin);
puts(line);
return 0;
}
如果您执行这样的程序:
If you execute the program like this:
$ ./readline
然后用户必须输入文本,然后按.
then the user must enter the text and press .
如果您执行这样的程序:
If you execute the program like this:
$ echo "Hello World" | ./readline
Hello World
$ ./readline < filename
First line of filename
然后stdin
将被连接到管道/重定向.你不用担心这一点,执行命令的外壳会执行工作(将stdin
连接到管道等),以便您的程序只需要从stdin
读取.
then stdin
will be connected to the pipe / redirection. You don't have toworry about this, the shell executing the command does the work (connecting stdin
to the pipes, etc) so thatyour program only need to read from stdin
.
如果您希望用户调用程序,则stdout
同样适用并在管道或重定向中使用输出,然后只需正常写入stdout
.外壳负责将stdout
连接到管道/重定向.
Same thing applies for stdout
, if you want that the user calls your programand uses the output in a pipe or redirection, then just write normally tostdout
. The shell takes care of connecting stdout
to the pipe / redirection.
这篇关于您如何使用C中文件的输入重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!