简体   繁体   English

如何使用命令行参数打开 C++ 中的文本文件,而不使用文件扩展名?

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

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.我正在编写一个 C++ 程序,其中我将文本文件的名称作为命令行参数传递,然后操作该文本文件。 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.我可以通过简单地打开存储在 argv[1] 中的文件名并在命令行上使用 .txt 来访问该文件。 But how would I do this without having to pass in.txt at the end?但是我怎么能做到这一点而不必在最后传递 in.txt 呢? 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.我尝试通过使用 argv[1] 并手动添加引号和 .txt 来执行此操作,但是当我尝试使用附加名称打开文件时出现错误。 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;}

You don't need double quotes for fileName , this should be enough: fileName不需要双引号,这应该足够了:

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

I'd would also add a check on argc to make sure an argument was actually given.我还会在argc上添加一个检查,以确保实际给出了一个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM