Fopen with stdin as a filename parameter

I was asked to write a program that basically parses the file provided to it with a stdin redirect, for example:
myProg param1 param2 param3 <theFileToParse

I am trying to use the fopen function to open a given file, but I do not understand what I should give in the argument `const char * filename '.

+4
source share
3 answers

You do not need to open the file. Your program has a special stdin value that contains a handle to the standard input of the process. You can use it in the same way as a file descriptor, for example:

 int c = fgetc( stdin ); 

or

 fread( somebuffer, somesize, 1, stdin ); 
+9
source

You don't have to open anything since stdin is redirected already , so you can just use this stdin handle with standard file functions, i.e.:

 while (fread(buf, 1, 1024, stdin) != 0) { // Read the data from input // Do something with data stored in buffer } 
+1
source

use freopen.

From the Unix man page:

  #include & lt stdio.h & gt

      FILE * freopen (const char * filename, const char * mode, FILE
      * stream);
0
source

All Articles