c++ - 为什么或何时我们将使用 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();
解决方案
推荐阅读
- sql - SQL - 如何计算期初余额和期末余额
- c - strtok 返回 null 但不返回 printf
- python - 在 plotly 中绘制带有几列的数据框
- docker - 带有电子邮件的 Keycloak 初始管理员用户
- python - 避免不必要的类声明
- c - 交替合并来自两个文本文件的文本
- javascript - 如何使用 .get() 访问新的 Map() 键和值
- flutter - Flutter:如何将文本拆分为 2 行
- c++ - 如何判断它是否在 C++ 中配置的时间之前?
- python - AttributeError:模块“keras.utils”没有属性“get_file”