How to : "ifstream inputFile = std::cin;" ?

Hi all,

I would like my application to use std::cin and std::cout, but with the possibility to pass file names as arguments : my_app -i input_file -o outputfile

Then the following pseudo code :

1
2
3
4
5
6
7
8
9
string inputFileName = "", outputFileName = "";
if (-i argument exist) inputFileName = <argument input_file>
if (-o argument exist) outputFileName = <argument output_file>
ifstream inputFile;
if (inputFileName != "") inputFile.open(inputFileName.c_str(), ifstream::in);
else inputFile = cin;
ofstream outputFile;
if (outputFileName != "") outputFile.open(outputFileName.c_str(), ifstream::out);
else outputFile = cout;


This is mainly to separate debug & release settings : I need to have a debug setting with files, and a release one with std::in/out. In the debug setting, while I use a file in place of std::cin, I want to keep std::cin as usual, for valgrind profiling tool interraction. So solutions with total redirection like freopen are not relevant for my use case.

How that can be done please ?
Last edited on
Cin and ifstream are both istream objects. Cout and ofstream are both ostream objects.

This function defaults to cout, but can take an ofstream.
1
2
3
4
void printData(int data, ostream& output = cout)
{
  output << data << endl;
}


If I remember correctly, you can have a if (output == cout), and that would work fine.
Thanks LowestOne,

From your indications, I did this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
			string inputFileName = "ti", outputFileName = "to";
			ifstream inputFile;
			istream* pCin = &cin;
			if (inputFileName != "") {
				inputFile.open(inputFileName.c_str(), ifstream::in);
				pCin = &inputFile;
			}
			ofstream outputFile;
			ostream* pCout = &cout;
			if (outputFileName != "") {
				outputFile.open(outputFileName.c_str(), ifstream::out);
				pCout = &outputFile;
			}
			char buff[500];
			pCin->getline(buff, 500);
			*pCout << buff << endl;


It works. With pointers I can use all stream methods without having to redefine them in a wrapper.
Also to note that cin and cout are standard io, which is defined at runtime (works for windows too).

myPrg.cpp
1
2
3
4
5
6
7
int main(void)
{
  string word;
  cin >> word;
  cout << word;
  return 0;
}


$ myPrg // This reads/prints to/from console
$ myPrg >input.txt //This reads from console and prints to intput.txt
$ myPrg <intput.txt //read from input, print to console
$ myPrg <intput.txt >output.txt //input.txt to output.txt
Last edited on
Topic archived. No new replies allowed.