Magical Toast
Magical Toast

Reputation: 47

How can I detect that input is being redirected in from a file?

I've written a program that takes its first argument and reverses the letters. So, for instance:

revstr cat

Will produce tac.

Now I want this to work when a file is redirected in. So, if filler.txt is a file containing "Now is the time for all good men to come to the aid of their country!", then:

revstr < filler.txt

Should produce:

!yrtnuoc rieht fo dia eht ot emoc ot nem doog lla rof emit eht si woN

But I don't know how to detect that such redirection is occurring!

This is what I've tried - obviously, it's no good. Where am I going wrong?

int main(int argc, char* argv[]) {
string temp,input,output;//store input from file, and get which file//

ofstream out("output.txt");

if(argc == 3)
{
    if(ifstream(argv[2]))
    {
        input = argv[2];
        ifstream in(input);
        while(in.good())
        {
            in >> temp;
            ReverseWord(temp);
            cout << temp << endl;
            out << temp << endl;
        }
    }
    else
        ReverseWord(argv[2]);


    }
    else
}

I'm fairly new to C++ and am doing my best to learn.

Upvotes: 0

Views: 1261

Answers (2)

JoergB
JoergB

Reputation: 4443

There are two possible approaches for you (well, you can even support both):

  1. You can accept a file name as command line argument (using a main that accepts arguments), then open an ifstream using this filename as the stream to read from. Users use your program like revstr filename.txt.
  2. You can read your input from std::cin. Then users need to use redirection to pass you the contents of a file. If your program is started using: revstr < filename.txt, then reading from std::cin will read the contents of the file. The program never even sees the filename.

You can support both by reading from an ifstream, if you get an argument, and from cin, if you don't get an argument. The function that does the reading can get the steam passed in as a generic istream&.

Upvotes: 4

Andy Prowl
Andy Prowl

Reputation: 126432

You should change your definition of your main() function so that it accepts arguments passed from command line:

int main(int argc, char* argv[])

The first variable will hold the number of command-line arguments provided, the second is a vector whose elements are pointers to NULL-terminated strings. These strings are the command-line arguments themselves. Please keep in mind, that the first string will always be the name of the executable.

For instance, supposing the name of the file to be opened will be passed as the first argument:

int main(int argc, char* argv[])
{
    std::string filename;
    if (argc > 1)
    {
        // Oh, there's some command line arguments here...
        filename = argv[0];
    }

    // Go on processing...
}

Upvotes: 0

Related Questions