gpt4 book ai didi

c - 如何在 C 中使用 execvp() 对文件进行排序并写入另一个文件

转载 作者:太空宇宙 更新时间:2023-11-04 13:03:23 25 4
gpt4 key购买 nike

假设我的主目录下有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

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

最佳答案

当您向 shell 键入 sort temp.txt > hello.txt 时,您不会传递 > hello。 txt 作为 sort 的参数。但是,当您如上所述调用 execvp 时,您将这些作为参数传递给排序。如果您希望 shell 将 > 视为重定向运算符,您需要将字符串传递给 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);
}

关于c - 如何在 C 中使用 execvp() 对文件进行排序并写入另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323449/

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