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?
            Asked
            
        
        
            Active
            
        
            Viewed 3,115 times
        
    0
            
            
         
    
    
        Ach113
        
- 1,775
- 3
- 18
- 40
- 
                    1@LiranFunaro - they asked for C - your link is about C++. C doesn't do `cin` and `cout`. For C, try reading something like this tutorial (I don't know how good it is - but surely you can Google some others on how to use `stdin` if it isn't what you need). https://www.cs.bu.edu/teaching/c/file-io/intro/ – JohnH Mar 13 '19 at 13:39
- 
                    1You have already open this file, `#inlude` and `fread(buff, size, 1, stdin);` – Igor Galczak Mar 13 '19 at 13:42
- 
                    2You don't open anything (your shell that does the input redirection did that), you just read from `stdin` the usual ways - `fgets()`, `getchar()`, `scanf()`, whatever. – Shawn Mar 13 '19 at 13:42
- 
                    Possible duplicate of [How do I read a string entered by the user in C?](https://stackoverflow.com/questions/4023895/how-do-i-read-a-string-entered-by-the-user-in-c) – Kamiccolo Mar 13 '19 at 13:49
- 
                    1The file is not "passed through stdin". The file *is* stdin. – William Pursell Mar 13 '19 at 13:49
- 
                    It seems I did not understand concept of stdin. I thought I had to pass it to some function. I got it working now – Ach113 Mar 13 '19 at 13:54
1 Answers
2
            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).
 
    
    
        Bodo
        
- 9,287
- 1
- 13
- 29