Passing function name in command line argument
How do I pass an argument value from the command line as a file name?
For example, if argv[1] contains the text "transplantPatient.txt"
would the code for declaring this be:
1 2
|
ifstream ArgFile;
ArgFile.open(argv[1]);
|
Thanks
Last edited on
This opens a file and displays the line number and line from file using argv[1].
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
|
// New template, do not delete
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
// Read from file
string line;
int count=0;
ifstream InFile (argv[1]);
if (InFile.is_open())
{
while ( getline (InFile,line) )
{
count++;
cout << count << " "<< line << '\n';
}
InFile.close();
}
else
{
cout << " Unable to open file" << endl;
return 1;
}
return 0;
}
|
You can also use argc to check how many command line arguments there are, if it's just a filename then argc will be 2.
Topic archived. No new replies allowed.