如何在不使用文件扩展名的情况下使用命令行参数打开C++中的文本文件?

How do you open a text file in C++ using a command line argument, without using the file extension?

本文关键字:文件 C++ 文本 参数 命令行 扩展名 情况下      更新时间:2023-10-16

我正在编写一个C++程序,在其中我将文本文件的名称作为命令行参数传递,然后操作该文本文件。但是我在引用文本文件时遇到问题。问题是,我希望能够引用仅通过其名称而不使用扩展名传入的文件。例如,我希望能够像这样引用代码:

./ProgramName exampleTextFileName

而不是这样的:

./ProgramName exampleTextFileName.txt

我只需打开存储在 argv[1] 中的文件名并在命令行上使用.txt即可访问该文件。但是,我该如何做到这一点而不必在最后传递.txt呢?我尝试通过采用 argv[1] 并手动添加引号和.txt来执行此操作,但是当我尝试使用附加的名称打开文件时出现错误。我假设文件名的变量类型实际上不是字符串?我该如何正确执行此操作?

这是我尝试使用的代码:

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;}

fileName不需要双引号,这应该就足够了:

...
string fileName = argv[1];
fileName += ".txt";
...

我还会添加对argc的检查,以确保确实给出了参数。