如何使用命令行参数写入和输出文件

How to write and output file using command line arguments

本文关键字:输出 文件 何使用 命令行 参数      更新时间:2023-10-16

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

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

那么,我该如何运行程序,将一行文本"Something like this"写入out.txt输出文件中呢。

因此,如果您的命令行看起来像./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;
}