【问题标题】:is there an easy way to get output of system commands into a string? [duplicate]有没有一种简单的方法可以将系统命令的输出转换为字符串? [复制]
【发布时间】:2017-01-24 22:04:19
【问题描述】:

有没有一种简单的方法可以将系统命令的输出转换为 C++ 中的字符串?

这是我的意思的例子,试图将时代变成一个字符串。 这当然行不通。

#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
int main(){
    string t = system("date +%s");
    cout << "Time " << t << endl;

    return 0;
    }

【问题讨论】:

  • 你的平台是什么?
  • 为什么不直接使用strftimetime
  • syetem() 返回什么?
  • 系统返回一个整数,0表示成功,-1表示失败。它不是系统命令的输出。

标签: c++


【解决方案1】:

对于该特定任务,您可能希望使用 timectime(或类似的东西)。

对于更一般的情况,请参阅popen(或者,在 Microsoft 编译器上,_popen)。这不会直接返回字符串;它返回一个FILE *,然后您可以像读取文件一样读取它。

【讨论】:

    猜你喜欢
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    相关资源
    最近更新 更多