C++ command arguments and a redirect

Sayth

Gawd
Joined
Oct 7, 2001
Messages
618
Hey all,

I have a small program that takes one of two argument switches and then runs. If no argument is given, it runs in interactive mode and asks you which option you would like.

My problem is that if I want to redirect the output to a txt file using >> the program reads it as an argument. How can I tell my code to allow redirect?

Code:
int main(int argc, char * argv[])
{
    std::cout << std::string(50, '\n');

    if (argc > 1)
    {
        if (std::string(argv[1]) == "-h")
        {
            function1();
        }
        else if (std::string(argv[1]) == "-s")
        {
            function2();
        }

        else
        {
            std::cout << " Please select a valid option." << std::endl;
            std::cout << "-h for function1" << std::endl;
            std::cout << "-s for function2" << std::endl;
            std::cout << "blank for interactive mode" << std::endl;
        }
    }
    else
        {
            interactiveMode();
        }
}
 
Okay to get around it, I made interactive mode its own argument. -i for interactive mode. Providing no option gives an error asking to select a valid option and provides a list of options.

Good enough for me! I hope this helps someone :)
 
File redirect (i.e. >>) works fine for me using VS2015. If I make a simple C++ Win32 console app that prints all arguments to stdout:

i.e.
test.exe -i blah.txt >> out.txt

produces file out.txt containing arguments test, -i, and blah.txt

Then again, what's passed to the app is a control of the OS and/or environment. If your command line has valid syntax, then the OS should only pass your app the relevant parts.
 
The redirection is performed by your shell; PowerShell or CMD.EXE on Windows, Bash or zsh or Korn or whatever else on Linux.
 
Back
Top