I am running a bunch of Linux commands from my C code using system() function. The result of running these commands from C code differs from the result when these commands are run from terminal. Example:
std::string name("\\pot\ ");
std::stringstream extractInfoCmd;
extractInfoCmd<<"find . -name \"*.info\" | xargs grep -E \"^PART|^"<<name.c_str()<<"\" >> information.rpt";
std::string extractInfoCmdStr = extractInfoCmd.str();
printf("\n##DEBUG Command: %s\n", extractInfoCmdStr.c_str());
system(extractInfoCmdStr.c_str());
If my input file contains these 2 lines:
PART: 6
\pot : f
Now if I execute the same command(received from DEBUG log above) from terminal, I got both lines. But if I execute the same command from C system() function, I get only first line, not the second line:
PART: 6
I have been debugging this since long and the cause of it is not striking to me.
The backslashes in the
namestring are getting interpreted by your compiler, and then you're using that string to build theextractInfoCmdstring, which you pass to the shell (/bin/sh) which tries to interpret them again. So the actual string that gets passed to thegrepprocess isn't the one you intend.Probably the best way to fix this is to avoid using
systemand instead use something likeexeclp, where you can pass each argument separately.There's also no need to use a pipeline to pass information from
findtogrep, you can do that withfinditself:Or, directly in C:
Rather than piping the output to a file using the shell, you can just use
pipein your process to get a pipe tofind's standard output directly, which you can then read from.