您如何使用C中文件的输入重定向? [英] How do you use input redirection from a file in C?

查看:113
本文介绍了您如何使用C中文件的输入重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编码的初学者,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 from stdin:

int main(void)
{
    char line[1024];

    fgets(line, sizeof line, stdin);

    puts(line);

    return 0;
}

如果您执行这样的程序:

If you execute the program like this:

$ ./readline

然后用户必须输入文本,然后按 ENTER .

then the user must enter the text and press ENTER.

如果您执行这样的程序:

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 to worry about this, the shell executing the command does the work (connecting stdin to the pipes, etc) so that your program only need to read from stdin.

如果您希望用户调用程序,则stdout同样适用 并在管道或重定向中使用输出,然后只需正常写入 stdout.外壳负责将stdout连接到管道/重定向.

Same thing applies for stdout, if you want that the user calls your program and uses the output in a pipe or redirection, then just write normally to stdout. The shell takes care of connecting stdout to the pipe / redirection.

这篇关于您如何使用C中文件的输入重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆