【问题标题】:C++, how to provide the input filename from the command line, without hardcoding it in the program?C++,如何从命令行提供输入文件名,而不在程序中硬编码?
【发布时间】:2014-02-14 21:29:39
【问题描述】:

这是我上一个问题的延续, In C++, how to read the contents of a text file, and put it in another text file?

在那,我能够打开一个输入文件input.txt并成功读取它的内容, 但现在我不想预先硬编码或给出输入文件名,

ifstream myfile ("input.txt");
if (myfile.is_open())

但我想稍后在编译程序并在命令行中生成一个名为test的可执行文件后给出输入文件名,如下所示

./test input.txt

关于如何做到这一点的任何建议?

【问题讨论】:

    标签: c++ filenames


    【解决方案1】:

    您可以在main 函数中访问传递给程序的命令行参数:

    int main(int argc, char *argv[]) { }
    

    argc 是传递给程序的参数数量,argv 包含指向保存传递给程序的参数的 C 字符串的指针。所以使用这个数组你可以访问传递给你的程序的参数。

    但是你必须注意:程序本身总是作为第一个参数传递给程序。所以 argc 总是至少为 1 并且argv[0] 包含程序名称。

    如果你想从你的帖子中访问input.txt,你可以写:

    int main(int argc, char *argv[]) {
       if (argc > 1) {
          // This will print the first argument passed to your program
          std::cout << argv[1] << std::endl;
       }
    }
    

    【讨论】:

    • 另外,std::vector&lt;std::string&gt; args(argv, argv + argc); 是访问参数的便捷方式。
    • 如果你使用argv+1而不是argv,如果你不需要它,你可以省略程序名称。 @Dan 这确实是访问参数的一种非常好的方式......
    【解决方案2】:

    只是为了添加所有答案 - 您可以使用 C/C++ 的“标准输入和输出”,例如 printf()scanf()

    $ ./a.out < input.file // input file
    $ ./a.out > output.file // output file
    $ ./a.out < input.file > output.file // merging above two commands.
    

    欲了解更多信息:REFER THIS

    当然,干净的方法是使用 argc/argv,正如各位先生所回答的那样。

    【讨论】:

    • 谢谢,这里的“a.out”是什么?是编译后生成的可执行文件,还是别的什么?
    • 是的,当您在 Unix 环境中编译您的 C++ 时,例如 'g++ sample.cpp' 将输出具有默认名称 a.out 的二进制可执行文件,否则您可以将输出文件的名称指定为 'sample_exec' 'g++ sample.cpp -o sample_exec'。然后类似地你可以运行 './sample_exec
    • 好的,谢谢,我在windows上工作,它正在生成.exe文件作为可执行文件
    • 没关系,重定向也适用于 Windows,但不确定。这个链接讲述了类似的事情(microsoft.com/resources/documentation/windows/xp/all/proddocs/…)。所以,原则上你可以做'sample.exe
    【解决方案3】:

    这就是 argvargc 的用途。

    int main(int argc, char **argv)
    {
        assert(argc >= 2); // Not the best way to check for usage errors!
        ifstream myfile(argv[1]);
        …
    }
    

    【讨论】:

      【解决方案4】:

      main 的 argc 和 argv 参数将包含程序的所有输入参数,通过 argc/argv google,或查看 answers here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-18
        相关资源
        最近更新 更多