5

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

2

2 Answers 2

11

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.
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.