将c中execl命令的输出保存到同一文件中

时间:2013-04-17 06:18:47

标签: c unix command-line exec multiple-processes

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAXLINE 512
main(int argc,char* argv[]){
    int k;

    for (k=1; k<=argc; k++) {
        if ((k%2)==0) {
            if (fork()==0){
                printf("asdsa");
                int fd; /*file descriptor to the file we will redirect ls's output*/

                if((fd = open("file1.txt", O_RDWR | O_CREAT))==-1){ /*open the file */
                    perror("open");
                    return 1;
                }

                dup2(fd,STDOUT_FILENO); /*copy the file descriptor fd into standard output*/
                dup2(fd,STDERR_FILENO); /* same, for the standard error */
                close(fd); /* close the file descriptor as we don't need it more  */

                /*execl ls */
                execl("/usr/bin/rev","rev",argv[k],NULL);
                exit(1);
            }
            else
            {
                wait(0);
            }

            char temp[512];
            sprintf(temp, "mv file1.txt %s",argv[k]);
            system((char *)temp);
        }
        else
        {
            if (fork()==0) {
                int fd; /*file descriptor to the file we will redirect ls's output*/

                if((fd = open("file2.txt", O_RDWR | O_CREAT))==-1){ /*open the file */
                    perror("open");
                    return 1;
                }

                dup2(fd,STDOUT_FILENO); /*copy the file descriptor fd into standard output*/
                dup2(fd,STDERR_FILENO); /* same, for the standard error */
                close(fd); /* close the file descriptor as we don't need it more  */

                execl("/usr/bin/awk","awk","-f","awk2.sh",argv[k],NULL);

                exit(1);
            }
            else
            {
                wait(0);                 
            }
            char temp[512];
            sprintf(temp, "mv file2.txt %s",argv[k]);
            system((char *)temp);
        }
    }
}

我尝试将文件file2.txt重命名为argv[k],但它不起作用。基本上,整个想法是将excel命令的结果保存在相同的文件argv [k]中。任何人都可以帮我这个吗?

编辑:argv[]是在命令行中作为参数给出的文件列表,例如“file1.txt”“file5.txt”等。

EDIT2: 让我假装我像

一样运行
$gcc program.c
$./a.out myfile.txt


myfile.txt
abc
efg

ouk2.awk所做的是保存在

file2.txt
cba
gfe

现在我想要的是用file2.txt的内容重写myfile.txt所以

myfile.txt
cba
gfe

但是这最后一步不起作用,它应该由系统命令完成但由于某种原因没有任何改变文件“myfile.txt”,在我启动程序后,我得到的只是

myfile.txt
abc
efg

file2.txt
cba
gfe

在我想要之前我是怎么说的

myfile.txt
cba
gfe

0 个答案:

没有答案