0

So i'm trying to understand command line arguments in c++ testing them out on this program:

#include <iostream>

int main(int argc, char* argv[])
{
    std::cout << "There are " << argc << " arguments:\n";

    // Loop through each argument and print its number and value
    for (int count{ 0 }; count < argc; ++count)
    {
        std::cout << count << ' ' << argv[count] << '\n';
    }

    return 0;
}

When I type this into the terminal

./a.out hello world file.txt

I get

There are 3 arguments:
0 ./a.out
1 hello
2 world
3 file.txt

But when I type this into the terminal

./a.out hello world <file.txt

I get

There are 2 arguments:
0 ./a.out
1 hello
2 world

where is the file.txt arguemnt goin and how do I use it?

  • The "<" will mean the console will open file and stream it to your application. So this part is already "parsed" by the command interpreter before calling your program. You should be able to pickup the content from std::cin – Pepijn Kramer Feb 02 '23 at 05:11
  • `>` and `<` are handled by your command interpreter (or shell) before it launches your program. So, given the command line `./a.out hello world < file.txt`, the shell will create a process with standard input redirected to (read from) `file.txt`, and the program `./a.out` will be started with 2 command line arguments `hello` and `world`. The specifics can (potentially) vary for different command interpreters or shells though. – Peter Feb 02 '23 at 06:01

0 Answers0