Hi. This is a bit unixy question. I'm trying to pipe output of one command to another and then process the pipe input into something more meaningful.
This is simplified code of what I am trying:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 256
int main(int argc, char *argv[]){
FILE *pipe;
char cmd[BUFFSIZE];
char buffer[BUFFSIZE];
const char *mode = "r";
strcpy(cmd, "ls -l");
if ( !(pipe= popen(cmd, mode)) )
{
perror("Pipe error");
exit(1);
}
int row;
row = 1;
while ( fgets(buffer, sizeof buffer, pipe));
{
printf("row %d: %s\n", row, buffer);
row++;
}
pclose(pipe);
return 0;
}
But instead off getting something like this:
Code:
row 1: file1.txt
row 2: file2.txt
row 3: file3.txt
...
I am geting this:
Code:
file1.txt
file2.txt
file3.txt
row 1: Dk
As you can see "row 1:" is printed at the end, and instead of anything usefull, Dk (garbage) gets printed after it.
What did I miss? I thought (f)gets gets input line by line. Is it possible that piped input doesn't contain line feed?
Thank you in advance and sorry if the question is already solved somewhere else (couldn't find it).