0

我使用 C 编写程序,其中使用 POPEN 执行系统命令。将每个命令的输出写入文件。我希望能够写入同一个文件并对命令的输出进行编号。

这是我打算做的输出。

假设我要运行的命令是..

1) ls 2) bash -版本

所以我想要的输出看起来像这样..

1) ls

*file.txt    file2.txt    file3.txt     file4.txt

2) bash -version

GNU bash, version 4.2.45(1)-release (i686-pc-linux-gnu)

这是我制作的代码:

FILE * out = NULL;
char * com = malloc(2000);
char * execCom = malloc(30000);
char * comR = malloc(2000);
strcpy(execCom, commands);
FILE * fp = NULL;

//remove("conf.txt")

out=fopen("com.txt","w");
dup2(fileno(out),1);
//run command and redirect the output to the file specified
if (execCom!=NULL)  
{
    fp=popen(com1,"w");
    fwrite(com2, 1,strlen(com2),fp);
    fwrite(com3, 1, strlen(com3),fp);

// get the first token 
com = strtok(execCom, "\n");

// walk through other tokens 
while( com != NULL ) 
{

    strcpy(comR,"\0");
    strcat(comR,com);
    strcat(comR,"\n");
    printf("%s",comR);

    //execute command
    fwrite(comR, 1, strlen(comR),fp);
    com = strtok(NULL, "\n");

}

pclose(fp);
fclose(out);

}

我能够将标准输出的输出重定向到一个文件,我使用 dup2 来实现这一点。然后知道 dup2 将 stdout 重定向到文件,我使用 printf,打印我想在文件中插入的字符串(我期望 printf 中的字符串将被重定向到同一个文件并将其插入到我想要的位置但它没有。)

这就是我得到的.. 是的,输出被重定向到文件以及 printf 中的字符串。但是,正如您在下面看到的,它没有按照我想要的方式格式化......

*file.txt    file2.txt    file3.txt     file4.txt
GNU bash, version 4.2.45(1)-release (i686-pc-linux-gnu)
1) ls
2) bash -version

我将如何做到这一点?谢谢!

4

0 回答 0