How can I redirect the execlp
output to a file? For example, I want to redire开发者_开发百科ct the output of execlp("ls", "ls", "-l", NULL)
to an output file(say a.txt).
You need to do something like this:
int fd = open("output_file", O_WRONLY|O_CREAT, 0666);
dup2(fd, 1);
close(fd);
execlp("ls", "ls", "-l", (char *)0);
The simplest way to do this would be to use freopen to open standard output on a new file:
FILE * freopen(const char *restrict filename, const char *restrict mode, FILE *restrict stream);
From the man page for fopen (which includes freopen):
The freopen() function opens the file whose name is the string pointed to by filename and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. The mode argument is used just as in the fopen() function.
So, in your case, something like:
#include <stdio.h>
FILE *myStdOut;
myStdOut = freopen("a.txt", "rw", stdout);
if (myStdOut == NULL)
// Error case, open failed
The particulars may vary from OS to OS and compiler versions.
精彩评论