开发者

redirecting the execlp output to a file

开发者 https://www.devze.com 2023-03-16 02:59 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消