I'm writing a program in C++ which do some special treatment for all the files in the current directory on Linux OS.
So i was thinking of using system calls such as system("ls")
to get the list of all files.
but how to store it then inside my program ? ( how to redirect the output of ls to let's say a string that i declared in the program )
Thanks
Before the C shell executes a command, it scans the command line for redirection characters. These special notations direct the shell to redirect input and output. You can redirect the standard input and output of a command with the following syntax statements: Item.
Regular output append >> operator The append >> operator adds the output to the existing content instead of overwriting it. This allows you to redirect the output from multiple commands to a single file.
The consensus seems to be not to use "ls". However, for anyone that is interested in a function to do this:
/**
* Execute a command and get the result.
*
* @param cmd - The system command to run.
* @return The string command line output of the command.
*/
string GetStdoutFromCommand(string cmd) {
string data;
FILE * stream;
const int max_buffer = 256;
char buffer[max_buffer];
cmd.append(" 2>&1"); // Do we want STDERR?
stream = popen(cmd.c_str(), "r");
if (stream) {
while (!feof(stream))
if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer);
pclose(stream);
}
return data;
}
I don't think you can use system to read the output.
Try using popen
.
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
But, you probably don't want to do this for ls
. Two reasons:
readdir
), instead of using shell commands and parsing it.ls
output is a bad idea.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With