Sunday, April 26, 2009

[Programming] executing reading system process in c

I was searching for reading the output of process in c running a process right from c program
system() command you already know I guess is a command used for executing a system command.
system("ls -l");
but here I will tell you a program which will read from a process and will inser its value in string and then you will be able to process it .......



#include
#include
#include
long int file_length(FILE *f)
{
long int pos;
long int end;

pos = ftell (f);
fseek (f, 0, SEEK_END);

end = ftell (f);
fseek (f, pos, SEEK_SET);

return end;
}

char *readfilestr(FILE *f)
{
char *r;
r=malloc(file_length(f)+1);
fread(r,file_length(f),1,f);
rewind(f);
r[strlen(r)-1]=0;
return r;
}
int main() {
FILE *in;
extern FILE *popen();
char *buff;

/* popen creates a pipe so we can read the output
of the program we are invoking */
if (!(in = popen("ls", "r"))) {
exit(1);
}

/* read the output of netstat, one line at a time */
buff=readfilestr(in);
printf("Output: %s", buff);


/* close the pipe */
pclose(in);
}


may be this will help all the developers for linux.

No comments:

Post a Comment