简体   繁体   English

如何在C中读取通过stdin传递的文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM