简体   繁体   中英

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 . 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?

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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