如何在 C 中使用 execvp() 对文件进行排序并写入另一个文件
how to use execvp() in C to sort a file and write into another file
假设我的主目录中有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 };
'proper' 方法是通过复制文件描述符自己进行重定向。类似于(为清楚起见省略了一些错误检查):
#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);
}
假设我的主目录中有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 };
'proper' 方法是通过复制文件描述符自己进行重定向。类似于(为清楚起见省略了一些错误检查):
#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);
}