I am trying to read a file from the command line passed as input. No not the filename. I'm not expecting the user to input a filename on the command-line, so that I could open it like this : fopen(argv[1], "r");
.
I am expecting a file like this : myprogram < file_as_input
. So whatever should go into argv is the contents of the file. How do I do this in C/C++ ?
When a program is invoked like this ./a.out < file
, the content of the file will be available on the standard input: stdin
.
That means that you can read this content by reading the standard input.
For example:
read(0, buffer, LEN)
would read the from your file.getchar()
would return a char from your file.On using redirection on the command line, argv does not contain the redirection.
The specified file simply becomes your stdin/cin.
So no need to open it using fopen
,just read from the 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
Output
Contents of input.txt seperated by space
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With