Search code examples
cstdin

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?


Solution

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