我正在写入redirect函数,将命令的输出写入给定的文件名。
例如:
echo Hello World > hello.txt会将“Hello World”写入hello.txt。
ls -al > file_list.txt会将当前目录中所有文件/目录名称的列表写入file_list.txt。
我的function到目前为止被定义为:
int my_redirect(char **args, int count) { if (count == 0 || args[count + 1] == NULL) { printf("The redirect function must follow a command and be followed by a target filename.\n"); return 1; } char *filename = args[count + 1]; //Concatenates each argument into a string separated by spaces to form the command char *command = (char *) malloc(256); for (int i = 0; i < (count); i++) { if (i == 0) { strcpy(command, args[i]); strcat(command, " "); } else if (i == count - 1) { strcat(command, args[i]); } else { strcat(command, args[i]); strcat(command, " "); } } //command execution to file goes here free(command); return 1; }
args[count]是">" 。
我如何执行由args[0]到args[count - 1]的string给出的命令到args[count + 1]给出的文件中?
编辑
这些是我们给的指示:
“通过为文件添加stdoutredirect来改进你的shell,只有在完成特性之后才能尝试。parsing行>,把之前的所有内容作为命令,第一个单词作为文件名(忽略<,>>,| etc )。
标准输出写出到文件描述符1(stdin是0,stderr是2)。 所以这个任务可以通过打开这个文件来实现,并且用dup2系统调用把它的文件描述符复制到1。
int f = open( filename , O_WRONLY|O_CREAT|O_TRUNC, 0666) ; dup2( f , 1 ) ;
注意:在这里使用系统调用打开不是库包装。“
如果允许以特殊的方式解决这个问题,那么它只适用于一小部分问题,比如捕获一个命令到一个文件的标准输出,你可以避免使用<stdio.h>的popen()函数重新发明轮子<stdio.h> 。
节目的草图:
> 。 FILE *cmd = popen(command, "r"); cmd流中读取行,写入输出文件 cmd流不EOF。 pclose(cmd) , fclose输出流 只有当你的教练不希望你使用fork,dup和朋友时,才能这样做。