如何在 C 中读取通过 stdin 传递的文件
How to read a file passed through stdin in C
我想像这样将文本文件传递给 C 程序 ./program < text.txt
。我在 SO 上发现像这样传递的参数不会出现在 argv[]
中,而是出现在 stdin
中。如何在标准输入中打开文件并读取它?
无需打开文件即可直接读取数据。 stdin
已经打开。如果不进行特殊检查,您的程序将不知道它是文件还是来自终端或管道的输入。
您可以使用 read
通过其文件描述符 0
访问 stdin
或使用 stdio.h
中的函数。如果该函数需要 FILE *
,您可以使用全局 stdin
.
示例:
#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 */
}
您还可以使用 scanf
读取和转换输入数据。此函数始终从 stdin
读取(与 fscanf
相反)。
我想像这样将文本文件传递给 C 程序 ./program < text.txt
。我在 SO 上发现像这样传递的参数不会出现在 argv[]
中,而是出现在 stdin
中。如何在标准输入中打开文件并读取它?
无需打开文件即可直接读取数据。 stdin
已经打开。如果不进行特殊检查,您的程序将不知道它是文件还是来自终端或管道的输入。
您可以使用 read
通过其文件描述符 0
访问 stdin
或使用 stdio.h
中的函数。如果该函数需要 FILE *
,您可以使用全局 stdin
.
示例:
#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 */
}
您还可以使用 scanf
读取和转换输入数据。此函数始终从 stdin
读取(与 fscanf
相反)。