how to write the output of a process executed using excel to a file in c


I am writing a c program in which it calls a process using execl() function. I get the output of the process along with my c program output. I need to store the output of the process called using execl() to a file. I know programming basics and also file input and output.

Here is my program:

printf("\nDisplaying output of ifconfig\n");


Displaying output of ifconfig

eth1      Link encap:Ethernet  HWaddr 02:00:00:a1:88:21

lo        Link encap:Local Loopback

I need to store the output of ifconfig in the file. How can i do it?

You can use popen to run the program instead of calling execl, and read the out and write it to a file. Or use the system function, which invokes a shell and therefore can contain full shell redirection.

Or open the file using open and then use dup2 to redirect it to STDOUT_FILENO.

Actually, using the exec functions like that is highly unusual. Normally you create a new process and call exec in the child process.

Using open and dup2 is what I suggest in this case:

#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>


/* Open the file for writing (create it if it doesn't exist) */
int fd = open("/path/to/file", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);

/* Make the standard output refer to the newly opened file */
dup2(fd, STDOUT_FILENO);

/* Now we don't need the file descriptor returned by `open`, so close it */

/* Execute the program */

Note: I do not have any kind of error handling in the above code, which you should have.