例如:
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时才这样做.
总结以上是内存溢出为你收集整理的编写我自己的linux shell I / O重定向’>’函数全部内容,希望文章能够帮你解决编写我自己的linux shell I / O重定向’>’函数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)