[英]redirecting the execlp output to a file
如何將execlp
輸出重定向到文件? 例如,我想將execlp("ls", "ls", "-l", NULL)
的輸出重定向到輸出文件(例如a.txt)。
您需要執行以下操作:
int fd = open("output_file", O_WRONLY|O_CREAT, 0666);
dup2(fd, 1);
close(fd);
execlp("ls", "ls", "-l", (char *)0);
最簡單的方法是使用freopen在新文件上打開標准輸出:
FILE * freopen(const char *限制文件名,const char *限制模式,FILE *限制流);
從fopen的手冊頁(其中包括freopen)中:
freopen()函數打開名稱為filename指向的字符串的文件,並將stream指向的流與其關聯。 原始流(如果存在)被關閉。 就像在fopen()函數中一樣使用mode參數。
因此,就您而言,類似:
#include <stdio.h>
FILE *myStdOut;
myStdOut = freopen("a.txt", "rw", stdout);
if (myStdOut == NULL)
// Error case, open failed
具體信息可能因操作系統而異,且操作系統和編譯器版本也有所不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.