Inputting file by dropping it on executable.
I made a program that inputs a file, and outputs another. To do this I used:
1 2
|
fileIn.open("fileIn.txt");
ofstream fileOut ("fileOut.txt");
|
Using this way to input a file the name has to be fileIn.txt, and be in the same directory as the program.
Is there a way using C++ to make it so you can drop a file with any name on the program, and the program will assign it to fileIn?
The way to do it is to parametrize your program on an
istream, and choose based upon the arguments given to your program. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int run( istream& ins )
{
string s;
unsigned n = 1;
while (getline( ins, s ))
{
n++;
}
cout << n << " lines\n";
return 0;
}
int main( int argc, char** argv )
{
if (argc == 2)
{
ifstream f( argv[ 1 ] );
if (!f)
{
cerr << "Could not open file " << argv[ 1 ] << endl;
return 1;
}
return run( f );
}
return run( cin );
}
|
Hope this helps.
What does this line do?
int main( int argc, char** argv )
I'm guessing it puts the file name in argv. What does it put in argc?
What is this line sending to run()?
return run( cin );
Okay, I am able to input a file, but now the output isn't working.
ofstream fileOut ("fileOut.txt");
It just isn't making "fileOut.txt".
Topic archived. No new replies allowed.