-1

Is there an easy way to get output of system commands into a string in C++?

Heres and example of what I mean, trying to get the epoch into a string. It doesnt work of course.

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

    return 0;
    }
j0h
  • 1,537
  • 3
  • 24
  • 45

1 Answers1

3

For that specific task you probably want to use time and ctime (or something similar).

For the more general case, see popen (or, on Microsoft compilers, _popen). This doesn't return a string directly; it returns a FILE *, which you can then read like you would a file.

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067