系统命令的管道输出到文件

Piping output of system command to file

我正在完成一项任务,我需要执行 运行 系统命令并将输出写入文件。目前,我可以在 运行 时间使用 >> output.txt 对输出进行管道传输,但是如何在我的程序中自动执行此操作而无需用户键入管道部分。我尝试在 system 函数本身中连接它,同时还尝试创建一个 temp 变量以将其附加在每个循环的开头。我已经很多年没有使用 C 了,所以我发现这项相对容易的任务很难。这是我的源代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[]) { /*argc holds the number of arguments and argv is an array of string pointers with indifinate size  */

    /*Check to see if no more than 4 arg entered */
    if(argc > 4 && argc > 0) {
        printf("Invalid number of arguments. No greater than 4");
        return 0;
    }
    FILE *fp;
    int i;
    char* temp[128];

    for(i = 1; i < argc; i++) {
        //strcopy(temp, argv[i]);
    //  printf("%s", temp);
        system(argv[i] >> output.txt);

    }
    return 0;
}

感谢大家的帮助。

此上下文中的 >> 不是 shell 重定向,而是 C 右移运算符。

重定向需要成为发送到 system 的命令的一部分。此外,temp 需要是 char 的数组,而不是 char *:

的数组
char temp[128];
sprintf(temp, "%s >> output.txt", argv[1]);
system(temp);