Linux   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了编写我自己的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) {
我正在编写重定向函数,将命令的输出写入给定的文件名.

例如:

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重定向’>’函数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。