带参数的main函数(命令行处理技术)

C++ 有一种让在命令行环境中运行的程序能够访问命令行参数的机制,方法是使用下面的 main() 函数:

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

例如:

program17.8.2

编写一个程序,将键盘输入(直到模拟的文件尾)复制到通过命令行指定的文件中。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
    ofstream fout;
    for (int file = 1; file < argc; file++)
    {
        fout.open(argv[file]);
        if(!fout.is_open())
        {
            std::cerr << " Can't open " << argv[file] << endl;
            exit(EXIT_FAILURE);
        }
        cout << "Enter input(enter a blank line to quit) " << endl;
        string input;
        while(getline(cin, input) && input.size() > 0)
        {
            fout << input << endl;
            cout << "Input over." << endl;
        }  
        fout.close();
    }
    return 0;
}

下面通过终端来执行该 cpp 文件。

在终端中进入到该 cpp 文件路径下:

 

 

先使用 g++ 命令生成可执行文件:

 

紧接着执行该可执行文件,同时带上程序中需要的参数,即一个文件名:

 

查看 a.txt 文件中的内容:

 

posted @ 2022-06-21 20:28  SanFranciscoo  阅读(178)  评论(0编辑  收藏  举报