将文件内容重定向到C中的另一个文件

问题描述

我正在编写一个简单的shell(用C语言编写),而我想使用的命令之一就是重定向

我有一个文件,我们称它为“输入”。我需要重定向到名为“输出”的新文件(或追加到一个文件)。我正在尝试编写一个可以使用exec ...命令和dup2()执行此操作的C程序,但是我只是在“输出”中得到一个空白文件。你能帮忙吗?

示例命令行输入:

输入>输出

(输入文件中包含文字

parsed是已解析的参数行的列表(以空格分隔)。因此,在这种情况下,parsed [0]是“输入”,parsed [1] =“>”,而parsed [2] =“输出

int position = 0; 
    while (parsed[position] != NULL)
    {
        if (strcmp(parsed[position],">") == 0)
        {
            int input_fd = open(parsed[position-1],O_RDONLY); //open file for read only
            if(input_fd == -1) //error reading file
            {
                perror("cannot open file for input.");
                fflush(stdin);
                printf("\n");
                fflush(stdin);
                status = 1; 
                close(input_fd);
                return status;
            }
            else //file open worked
            {
                if (parsed[position+1] == NULL)//no output file name given,exit 
                {
                    perror("cannot open output file,no file name given.\n");
                    fflush(stdin);
                    status = 1;
                    close(input_fd); 
                    return status;
                }
                
                int result = dup2(input_fd,0);
                if (result == -1)//if error duplicating
                {
                    perror("error at source dup2()");
                    fflush(stdin);
                    status = 2;
                    close(input_fd); //close input file
                    return status;
                }
                
                int output_fd = open(parsed[position+1],O_WRONLY | O_CREAT | O_APPEND,0644);
                if (output_fd == -1) //if error opening
                {
                    perror("error at output_fd open()");
                    fflush(stdin);
                    status = 1;
                    close(input_fd); //close input file
                    close(output_fd); //close output file
                    return status;
                }
                
                result = dup2(output_fd,1);

                execvp("grep",parsed);

                close(input_fd);
                close(output_fd);
                
                status = WEXITSTATUS(status);
                return status; 

            }
        }
        position++;
    }

我正在尝试execvp(“ grep”,已解析)认为这会将内容发送到新文件,但是显然它不起作用,但是我对于从这里去哪里感到困惑! (我是dup2和exec的新手。)

任何帮助或指导将不胜感激!

* edit:正如某人指出的那样,我将需要对此进行分叉并运行一个子进程。我正在努力...现在我只想看看是否可行(我可以在执行后退出它……)

** edit:我已将exec函数切换为execlp(“ cat”,parsed [position + 1],NULL);这似乎可行...但是我不太确定为什么。我假设并告诉我如果我错了,它将打印出parsed [position-1](这是我的输入文件名)到输出(“ cat”调用),该输出重定向到parsed [position + 1] ,这是我的输出文件,以NULL结尾。正确吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)