Home > other >  Using system() call in c to echo to a file -- string literal is always used instead of > operat
Using system() call in c to echo to a file -- string literal is always used instead of > operat

Time:10-14

Using posix and c I am trying the following:

std::string command = "echo 1 > myFile";
system(command);

The output when ran is always "1 > myFile" output to the terminal, instead of 1 being written to the file. Thoughts on if this is possible, or how to fix? Underlying system is linux and bash.

CodePudding user response:

The documentation of std::system says that it "Calls the host environment's command processor". If that is not happening, consider forcing the issue with something akin to

system("/bin/sh -c 'echo 1 > myFile'")

CodePudding user response:

Since you're on linux, you can use popen

#include<cstdlib>
#include<memory>

const char *cmd = "echo 1 > myFile";
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
  • Related