Executing Shell Commands with system() and popen() in C

If you want to run shell commands from within a C program there are several options:

Pipe to/from Shell with popen() (and pclose())

Prototypes:

FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);

Note that a pointer (FILE *) is initialized for just one call, and that after the call the file should be closed. In between you can read from the thus created file with fscanf() and other file-reading functions, alternatively write to it with fprintf() and other file-writing functions.

Typical usage is:

FILE *fp;
char *command;

/* command contains the command string (a character array) */

/* If you want to read output from command */
fp = popen(command,"r");
     /* read output from command */
      fscanf(fp,....);   /* or other STDIO input functions */

fclose(fp);

/* If you want to send input to command */
fp = popen(command,"w");
     /* write to command */
      fprintf(fp,....);   /* or other STDIO output functions */

fclose(fp);

The program cannot both send input to the command and read its output. The file (handle) fp behaves like an ordinary STDIO file.

Buffered I/O with fdopen()

If you elect to bypass the shell, it can be handy to have buffered I/O. STDIO functions are available on a file descriptor with fdopen, which associates a stream to a file descriptor.

FILE *fdopen(int fd, const char *mode);

After this call, STDIO buffered I/O and standard I/O functions such as scanf() and printf() can be used on fd.