I'm writing a C++ program where I pass the name of a text file as a command-line argument and then manipulate that text file. But I'm having trouble referencing the text file. The thing is, I want to be able to reference the file passed in just by its name without the extension. For example I want to be able to reference the code like this:
./ProgramName exampleTextFileName
and not like this:
./ProgramName exampleTextFileName.txt
I'm able to access the file by simply opening the file name stored in argv[1] and using .txt on the command line. But how would I do this without having to pass in .txt at the end? I tried doing this by taking argv[1] and manually adding quotation marks and .txt, but I get an error when I try to open the file using the appended name. I assume the variable type for file names is not actually a string? How would I do this correctly?
Here is the code I was trying to use:
int main(int argc, char *argv[]) {
string line;
string fileName;
fileName = argv[1];
fileName = "\"" + fileName + ".txt\"";
cout << fileName;
ifstream myfile (fileName);
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;}