简体   繁体   English

创建用于Shell输出重定向的文件

[英]creating file for shell output redirection

This is a school assignment. 这是学校的作业。

So basically I have written a C code for a shell that handles terminating the command with & , and input / output redirection using > or <. 因此,基本上,我为外壳编写了C代码,该外壳处理了用&终止命令并使用><.输入/输出重定向的方法<. using pipes and fork() , execvp() . 使用管道和fork()execvp()

The problem is my input/output redirection only handles that for files that already exist . 问题是我的输入/输出重定向仅处理已经存在的文件。

What i need to know is how would I go about redirecting output to a file that doesn't exist - I know I would have to create the file, but I'm not sure how that works. 我需要知道的是如何将输出重定向到不存在的文件-我知道我必须创建该文件,但是我不确定该如何工作。

For example: ls -a < test.txt 例如: ls -a < test.txt

If test.txt is not in the directory, i need to create it and redirect output to that. 如果test.txt不在目录中,我需要创建它并将输出重定向到该目录。 So how do I create this file? 那么如何创建此文件?

here is some basic example code which does not create a new file: 这是一些不创建新文件的基本示例代码:

        else if( '>' ==  buff[i] ){
           i++;
           j=0;

           if( ' ' == buff[i] ) 
              i++;

           while( ' ' != buff[i] && i < len )
              out_file[j++]=buff[i++];
           out_file[j]='\0';


           if ( ( ofd = open(out_file,1) ) < 0 ){
              perror("output redirected file");
              exit( 1 );
           }

           close(1);
           dup(ofd);
        }

Any help with how I can output and create a new file would be much appreciated! 我如何输出和创建新文件的任何帮助将不胜感激! Thanks! 谢谢!

You need to tell open to create the file, if necessary: 如果需要,您需要告诉open创建文件:

if ( ( ofd = open(out_file, O_WRONLY | O_CREAT) ) < 0 ) {

Note that your code will be more readable if you use the named constants for the flags to open . 请注意,如果您使用命名常量open标志,则代码将更具可读性。 Compare with the functionally equivalent 与功能相当的产品比较

if ( ( ofd = open(out_file, 513) ) < 0 ) {

or even 甚至

if ( ( ofd = open(out_file, 0x0201) ) < 0 ) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM