大佬教程收集整理的这篇文章主要介绍了编写我自己的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.“
以上是大佬教程为你收集整理的编写我自己的linux shell I / O重定向’>’函数全部内容,希望文章能够帮你解决编写我自己的linux shell I / O重定向’>’函数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。