Saturday, June 12, 2010

Who is popen()?

I found a new function called popen() in stdio.h. This is so interesting that this function wasn't in the C Programming Language (ANSI) but can be found in the Standard C Library book, according to this page. This function is useful where it can direct the *NIX (e.g. ls -l) command into a FILE pointer, and read the desire output from that pointer.

For example, ls -l command was type in the console like this:
huahsin68@huahsin68-laptop:~/Development/TestLab$ ls -l
total 12
drwxr-xr-x 3 huahsin68 huahsin68 4096 2010-06-12 19:45 Debug
-rw-r--r-- 1 huahsin68 huahsin68 241 2010-03-27 15:00 MyLog.000.txt
drwxr-xr-x 4 huahsin68 huahsin68 4096 2010-03-27 12:19 src
the same thing can be done using popen(), each line of the output will be direct to FILE pointer. Use fgets() to retrieve each line of the output. Below is the sample code:
FILE *fp;
char line[130];

fp = popen("ls -l", "r");
while ( fgets( line, sizeof line, fp)) {
   printf("%s", line);

No comments: