Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file as input from the command line

Tags:

c++

c

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++ ?

like image 850
Mayank Kumar Avatar asked Dec 08 '22 14:12

Mayank Kumar


2 Answers

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.
like image 157
Xaqq Avatar answered Dec 22 '22 03:12

Xaqq


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

like image 33
P0W Avatar answered Dec 22 '22 03:12

P0W