所以我了解到,要读取和打印一行文本,您只需使用 printf
、scanf
并键入即可。但是,如果我想打印出一个文本文件而不在终端中输入它们怎么办?我并不是说在只能打开特定文件的地方使用 fopen(filename, "r")
。我认为这称为重定向,但我无法理解它。如下输入示例所示:
./myprogram < input.txt
最佳答案
这是一个redirection cheat sheet .我们感兴趣的是:
cmd < file
: Redirect the contents of the file to the standard input (stdin) of cmd.
这是一个简单的例子,它会打印你的 input.txt
的内容。文件。与手动输入相比,程序永远不会等待,会循环直到到达文件末尾(注意:有些情况下没有结束,您可能需要添加替代的中断条件)。
#include <stdio.h>
int main(void)
{
char buffer[100];
while (fgets(buffer, 100, stdin))
printf("%s", buffer);
return (0);
}
-
./myprogram < input.txt
将打印您的 input.txt -
./myprogram
将等待您的手动输入并打印您刚刚输入的内容。
关于c - 从终端行读取文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57943026/