首页 > 解决方案 > 为什么或何时我们将使用 linux 命令调用系统函数而不是编写 C/C++ 代码?

问题描述

我是Linux新手。。

我编写了 C++ 代码,在其中使用 linux / shell 命令调用系统函数。调用系统函数要容易得多-编写的 C/C++ 代码更少,运行或考虑所有可能情况的测试更少……我的问题是为什么或何时我们更喜欢 C/C++ 代码而不是使用 linux/ 进行系统调用外壳函数?我只看到优势——开发时间更短,更稳定(shell 命令涵盖了所有可能的情况)。

我们只使用 linux(不打算将代码移至 windows 或其他平台)。

例如,这是我的代码 - 从日志中提取晚于“时间”写入的行(使用系统函数调用“awk”):

#define BUF_LEN 1024

string time = "2019-01-09T23:32:36";//Just for example
string path_to_log = "path to a log";
string output_path = "...";
string cmd_r = "awk '$0 > \"" + time  + "\"' " + path_to_log;
string result;

std::ofstream outfile(output_path);
if(!outfile.is_open())
{        
    printf("Error. Can't open file: [%s]", output_path.c_str());
    return;
}

//Run command to extract lines
char buf[BUF_LEN];
FILE* pipe = popen(cmd_r.c_str(), "r");

if (pipe)
{
    while (fgets(buf, BUF_LEN, pipe) != NULL)
    {
       result.append(buf);
       outfile << buf;
     }
 }
pclose(pipe);
outfile.close();

标签: c++shell

解决方案


推荐阅读