【问题标题】:Piping output of system command to file将系统命令的输出通过管道传输到文件
【发布时间】:2018-08-27 17:38:59
【问题描述】:

我正在执行一项任务,我需要运行系统命令并将输出写入文件。目前,我可以在运行时使用 >> 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;
}

感谢大家的帮助。

【问题讨论】:

    标签: c operating-system pipe system


    【解决方案1】:

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

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

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

    【讨论】:

    • 好的,我明白这一点,但我在将 temp 放入 sprintf 时遇到问题。我不能将 char[128] 与 *char 类型一起使用。我尝试删除 temp char 指针的大小,但随后出现段错误。我不知道该怎么办。
    • 您已将 temp 声明为指针数组,而不是 char 数组。
    • 非常有帮助,感谢您的解释!
    猜你喜欢
    • 2018-08-18
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多