I/O Redirect Unix/C++

Looking to use C++ to take input from a file in Unix.
Filename could be any name at any address such as:
 
$ ./a.out < /some_address/inputfile.txt


In my file I'm just trying to open it and put every space separated value in a vector (assuming integers for now). Whats the problem I keep getting my "unable to open" condition.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Assume correct includes
int main(int argc, char *argv[]) {
    ifstream infile (argv[1]);

    if ( !infile.is_open() )
      cout << "Could not open file!" << endl;

    else{ 
      vector<int> vec;
      string line;
      int val;
    
      getline(infile, line);
    
      stringstream stream(line);
    
      while (stream >> val)
         vec.push_back(val);
     }
    return 0;
}
Pay attention to the < in the command. It has a special meaning. It makes so that when the program reads input (using std::cin, std::scanf, etc.) it will read it from the file you have on the right instead of the terminal. Your program does not receive any arguments. Simply use std::cin to read the input.

http://en.wikipedia.org/wiki/Redirection_%28computing%29
Last edited on
Ah, thanks. I was under the impression it was just giving file name.
Topic archived. No new replies allowed.