【问题标题】:How to write and output file using command line arguments如何使用命令行参数写入和输出文件
【发布时间】:2014-10-19 07:55:40
【问题描述】:

我正在尝试使用命令行参数将一行文本传递到输出文件中。我知道您可以使用输入文件来执行此操作。 我正在使用 unix 运行一个程序,我编译它并像这样运行它:

g++ -o program program.C 
./program

那么我将如何运行程序以将一行文本“类似这样”写入 out.txt 输出文件。

【问题讨论】:

  • 你是在问如何从程序内部写入文件,或者如何redirect从中输出?
  • 嗯,我想重定向它的输出。
  • 要从你的程序重定向输出并创建/覆盖out.txt,在你的shell中输入./program > out.txt。要追加,请键入 ./program >> out.txt。要捕获 out.txt 中的标准错误 (std::cerr) 输出,请尝试 ./program 2>&1 > out.txt。您可以在 shell 手册页中阅读这些内容 - 例如输入“ps”以查看您的 shell 是否为 bashkshtcshashzsh 等,然后输入 man bash(或其他)来阅读手册页。

标签: c++ unix command-line-arguments


【解决方案1】:

因此,如果您的命令行看起来像 ./program <filename> <text_to_append>,则以下内容将起作用:

#include <fstream>

int main(int argc, char * argv [])
{
    // first argument is program name
    if (argc == 3)
    {
        std::ofstream ofs;
        ofs.open (argv[1], std::ofstream::out | std::ofstream::app);  
        ofs << argv[2];
        ofs.close();
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 2012-10-22
    • 2020-02-29
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多