【问题标题】:how to use execvp() in C to sort a file and write into another file如何在 C 中使用 execvp() 对文件进行排序并写入另一个文件
【发布时间】:2016-01-24 05:39:58
【问题描述】:

假设我的主目录中有 temp.txt,我想对这个文件中的所有数据进行排序,并将所有排序后的数据写入另一个名为 hello.txt 的文件中。这是我尝试过的代码(编程 c):

#include <stdio.h>
#include <stdlib.h>

int main(int agrc,char *argv[]){
    char *argv1[]={"sort","temp.txt",">", "hello.txt",NULL};
    printf("hello I will sort a file\n");

    execvp(argv1[0],argv1);



}

这是我的程序,终端总是给我一条错误消息,即

hello I will sort a file
sort: cannot read: >: No such file or directory

谁能告诉我我的代码有什么问题?有人可以告诉我如何解决吗?感谢您的帮助!

【问题讨论】:

    标签: c linux unix exec execvp


    【解决方案1】:

    当您在 shell 中键入 sort temp.txt &gt; hello.txt 时,您不会&gt;hello.txt 作为参数传递给 sort。但是,当您像上面那样调用execvp 时,您正在将它们作为参数传递给排序。如果您希望 shell 将 &gt; 视为重定向运算符,则需要将字符串传递给 sh 并让它对其进行评估:

    char *argv1[]={ "sh", "-c", "sort temp.txt > hello.txt", NULL };
    

    执行此操作的“正确”方法是通过复制文件描述符自己进行重定向。类似的东西(为了清楚起见省略了一些错误检查):

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    
    
    int
    main( int argc, char **argv )
    {
        int fd;
        const char *input = argc > 1 ? argv[1] : "temp.txt";
        const char *output = argc > 2 ? argv[2] : "hello.txt";
        char * argv1[] = { "sort", input, NULL };
    
        fd = open( output, O_WRONLY | O_CREAT, 0777 );
        if( fd == -1 ) {
            perror(output);
            return EXIT_FAILURE;
        }
    
        printf("hello I will sort a file\n");
        fclose(stdout);
        dup2( fd, STDOUT_FILENO);
        close(fd);
        execvp(argv1[0],argv1);
    }
    

    【讨论】:

    • 谢谢,很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多