gpt4 book ai didi

c - 将系统命令的输出通过管道传输到文件

转载 作者:行者123 更新时间:2023-11-30 14:46:41 24 4
gpt4 key购买 nike

我正在做一项作业,要求我运行系统命令并将输出写入文件。目前,我可以在运行时使用 >> 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 右移运算符。

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

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

关于c - 将系统命令的输出通过管道传输到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52044416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com