How to read a file passed through stdin in C

邮差的信 提交于 2021-01-29 06:50:14

问题


I want to pass a text file to a C program like this ./program < text.txt. I found out on SO that arguments passed like that dont appear in argv[] but rather in stdin. How can I open the file in stdin and read it?


回答1:


You can directly read the data without having to open the file. stdin is already open. 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. If the function requires a FILE * you can use the global 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. This function always reads from stdin (in contrast to fscanf).



来源:https://stackoverflow.com/questions/55143159/how-to-read-a-file-passed-through-stdin-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!