'Reading arguments from a text file using <

I have a txt file called test.txt that looks like this,

hi this is a test

and I have a c++ file called selection_sort.cpp that looks like this,

#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
    
    cout << argc << endl;
    for (int i = 0; i < argc; i++) {
        cout << argv[i] << endl;
    }
    return 0;
}

right now when I compile my program in my terminal with

g++ selection_sort.cpp -o selection_sort

and then try and print out all of of the arguments I am trying to pass using my code like this

./selection_sort < test.txt

but it only outputs

./selecton_sort

I would like it to output

./selection_sort
hi
this
is
a
test

What am I missing or doing wrong? I need to use the <.



Solution 1:[1]

What am I missing or doing wrong? I need to use the <.

This is a shell operator that sends the content of the file to the standard input of the application.

./app < text.file

Will read the file text.file and send the conent to the standard input of the application app. In C++ you can read the standard input via std::cin.

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{    
    std::string word;
    while (std::cin >> word) {
        std::cout << word << "\n";
    }
}

Solution 2:[2]

< in bash is used to redirect input. In other words, it redirects the standard input for your process to the file. However, command line arguments (e.g. argv arguments) are not read through standard input, so you cannot capture them from a file by redirecting input.

Rather, they are provided as arguments when running the command in bash to begin with. You can accomplish your goal like so:

./selection_sort $(cat test.txt)

cat is for concatenating files, but if you supply it just one file, it will just output the contents of the file through standard out. The $(x) operation will execute the x command in a subshell, capture its standard output (which in this case is the contents of the file), and then do variable substitution to replace $(x) with said contents.

Edit:

Or, you can just change the way the arguments are accepted, so that they are accepted via standard input. It depends on how you want to be able to run the program.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin York
Solution 2 Alexander Guyer