Reputation: 155
I want to run my code and send my file in 2 ways
myprogram < input.txt
or cat input.txt | myprogram
myprogram input.txt
I have figured out the secong way using argc
and argv[]
but I am not able to figure out how to write the code for the first option.
int main (int argc, char *argv[])
{
ifstream fin;
if(argc > 1){
fin.open (argv[1]);
}
else
}
Upvotes: 0
Views: 807
Reputation: 84521
As mentioned above in the comment, a portable way is passing either the open file or std::cin
as an istream
reference to a function and doing your input there. In that case either the file or std::cin
may be passed. E.g.
#include <iostream>
#include <fstream>
#include <string>
void readinfo (std::istream& in)
{
std::string s;
while (in >> s)
std::cout << s << '\n';
}
int main (int argc, char **argv) {
if (argc > 1) { /* read from file if given as argument */
std::ifstream fin (argv[1]);
if (fin.is_open())
readinfo (fin);
else {
std::cerr << "error: file open failed.\n";
return 1;
}
}
else { /* read from stdin */
readinfo (std::cin);
}
return 0;
}
A non-portable Linux only option reading from /dev/stdin
if no file is given simply requires a ternary operator, e.g.
std::ifstream fin (argc > 1 ? argv[1] : "/dev/stdin");
if (!fin.is_open()) {
std::cerr << "error: file open failed.\n";
return 1;
}
/* read from fin here */
Neither are completely elegant, but both support (subject to the OS constraint)
myprogram < input.txt
or
myprogram input.txt
Upvotes: 5
Reputation: 1737
You want to read from stdin, and for that there's 2 options:
std::cin
fread()
and other C-style IOstd::cin >>
https://en.cppreference.com/w/cpp/io/cin has the advantage of reading formatted text into some binary representation https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
C-style IO https://en.cppreference.com/w/cpp/io/c has the advantage of reading binary data well.
It depends on what you want to do with it your input
Upvotes: -2