Wednesday, April 18, 2012

Run SYSTEM command and get output in C

#include 
#include
int main( int argc, char *argv[] )
{
FILE *fp;
int status;
char path[1035];
/* Open the command for reading. */
fp = popen("/bin/ls /etc/", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}
/* close */ pclose(fp);
return 0;
}




We can parse the string path by following concept for example

(Consider my input) -> hi, Me A. 2154
it suppose to return:
hi
Me
A
2154



Then following Program will help you,



#include
#include
int main(void)
{
char message[50], *current, *last;

gets(message);
last=message;

current=strtok(last, ",");
puts(current);

current=strtok(NULL, " ");
puts(current);

current=strtok(NULL, ".");
puts(current);

current=strtok(NULL, " ");
puts(current);

current=strtok(NULL, " ");
puts(current);

current=strtok(NULL, " ");
puts(current);

return;
}



STRTOK()

A sequence of calls to strtok() breaks the string pointed to by s1 into a sequence of tokens,
each of which is delimited by a byte from the string pointed to by s2.
The first call in the sequence has s1 as its first argument,
and is followed by calls with a null pointer as their first argument.
The separator string pointed to by s2 may be different from call to call.

No comments:

Post a Comment