[英]How to read a file passed through stdin in C
I want to pass a text file to a C program like this ./program < text.txt
. 我想将文本文件传递给像这样的C程序
./program < text.txt
。 I found out on SO that arguments passed like that dont appear in argv[]
but rather in stdin
. 我在SO上发现像这样传递的参数不会出现在
argv[]
,而是出现在stdin
。 How can I open the file in stdin and read it? 如何在stdin中打开文件并阅读?
You can directly read the data without having to open the file. 您可以直接读取数据,而无需打开文件。
stdin
is already open. stdin
已经打开。 Without special checks your program doesn't know if it is a file or input from a terminal or from a pipe. 如果没有特殊检查,您的程序将不知道它是文件还是来自终端或管道的输入。
You can access stdin
by its file descriptor 0
using read
or use functions from stdio.h
. 您可以使用
read
或使用stdio.h
函数通过其文件描述符0
访问stdin
。 If the function requires a FILE *
you can use the global stdin
. 如果函数需要
FILE *
,则可以使用全局stdin
。
Example: 例:
#include <stdio.h>
#define BUFFERSIZE (100) /* choose whatever size is necessary */
/* This code snippet should be in a function */
char buffer[BUFFERSIZE];
if( fgets(buffer, sizeof(buffer), stdin) != NULL )
{
/* check and process data */
}
else
{
/* handle EOF or error */
}
You could also use scanf
to read and convert the input data. 您也可以使用
scanf
读取和转换输入数据。 This function always reads from stdin
(in contrast to fscanf
). 此函数始终从
stdin
读取(与fscanf
相反)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.