1

How do I get the filename from redirection from the shell in my C++ code? i.e. ./MyProgram < myfile , I want to get myfile as the filename and its content line by line.

**Edit: I managed to get the input from file. Thanks for the help. However, after the looping through the file content, I want to keep user input with cin. It's like this:

while (true)
{
    if (cin.eof() == false)
    {
        getline(cin, line);
        cout << line;
    }else{
        cin >> choice;
    }
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Amumu
  • 17,924
  • 31
  • 84
  • 131
  • If the standard input is redirected from the file, there is no more input to read after you get EOF on standard input; that's what EOF means. If you want to read from the terminal, then you probably don't want to support the I/O redirection. – Jonathan Leffler Mar 21 '11 at 04:01
  • Also, your question has essentially nothing to do with pipes as it stands - please retitle it appropriately. – Jonathan Leffler Mar 21 '11 at 04:03
  • You really should revert your edit, clarifying a question is good, changing the question to something entirely different is bad. I'd say to ask your new question as a separate question, but it's already been answered many times. Use `while (cin.getline(line))`. – Ben Voigt Mar 21 '11 at 05:00
  • New question is a duplicate of http://stackoverflow.com/questions/2251433/checking-for-eof-in-stringgetline – Ben Voigt Mar 21 '11 at 05:01

2 Answers2

8

You can't (at least not portably). This information is not provided to the program. Instead, you can access the data from myfile (in your example) by reading from standard input. E.g., you can use C++'s getline with cin as the first parameter.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • But I have to read from a file for input from the command above, not by manually entered by typing. Is there a way to get the whole line? – Amumu Mar 21 '11 at 02:58
  • You can get the data from `myfile` by reading standard input. That is the point of the redirection operator. It lets a program read user input the same way it reads a redirected file. – Matthew Flaschen Mar 21 '11 at 03:11
  • Ok I did it. However, I want to keep user input after reading file with cin, and it didn't work. It keeps looping forever. I will modify my first post. – Amumu Mar 21 '11 at 03:47
2

Depending on the shell, you may have inherited a descriptor representing an actual file or a pipe. If it's an actual pipe (i.e. fifo), the name won't mean much. But you can get the name on linux (and on Windows, but it doesn't sound like you're interested in that).

See Getting Filename from file descriptor in C

Community
  • 1
  • 1
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720