编写我自己的linux shell I / O重定向’>’函数
我正在编写重定向函数,将命令的输出写入给定的文件名.
例如: echo Hello World> hello.txt会将’Hello World’写入hello.txt. ls -al> file_list.txt会将当前目录中所有文件/目录名称的列表写入file_list.txt. 到目前为止,我的功能定义为: 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," "); } } //command execution to file goes here free(command); return 1; } 其中args [count]是“>”. 如何执行args [0]到args [count-1]的字符串给出的命令到args [count 1]给出的文件? 编辑 这些是我们给出的指示: “通过向文件添加stdout的重定向来改进你的shell.只有在完成功能后才尝试1.为>解析行,将所有内容作为命令,然后将第一个单词作为文件名(忽略<,>> ;,|等). 标准输出被写出到文件描述符1(stdin为0,stderr为2).因此,可以通过打开文件,并使用dup2系统调用将其文件描述符复制到1来实现此任务. int f = open( filename,O_WRONLY|O_CREAT|O_TRUNC,0666) ; dup2( f,1 ) ; 注意:使用系统调用open not library wrapper fopen here.“ 解决方法
如果允许您以特殊方式解决此问题,那么它仅适用于一系列问题,例如将命令的stdout捕获到文件中,您可以使用< stdio中的popen()函数重新发明轮子.H取代. 该计划草图:
>确定输出文件名 >打开输出文件进行写入 >确定命令和参数 >构造从args到>的命令字符串. >调用FILE * cmd = popen(命令,“r”); >从cmd流读取行,写入输出文件 >在cmd流上没有EOF的情况下转到6. > pclose(cmd),fclose输出流 只有当您的教师不希望您使用fork,dup和friends时才这样做. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |