Reading a file as command line input

I am trying to read a file from the command line passed as input. No file name. I do not expect the user to enter a file name on the command line so that I can open it as follows: fopen(argv[1], "r"); .

I expect a file like this: myprogram < file_as_input . So all that should be in argv is the contents of the file. How to do it in C / C ++?

+4
source share
2 answers

When you call a program such as ./a.out < file , the contents of the file will be available on standard input: stdin .

This means that you can read this content by reading standard input.

For instance:

  • read(0, buffer, LEN) will read from your file.
  • getchar() will return char from your file.
+11
source

When using redirection on the command line, argv does not contain redirection.

The specified file just becomes your stdin / cin.

Therefore, there is no need to open it with fopen , just read from standard input.

Example:

 using namespace std; int main() { vector <string> v; copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(v)); for(auto x:v) cout<<x<<" "; return 0; } 

test <input.txt

Exit

The contents of the input.txt section, separated by a space

+3
source

Source: https://habr.com/ru/post/1493910/


All Articles