繁体   English   中英

从命令行将输出重定向到C中的文本文件

[英]Redirecting output to a text file in C from the command line

我在c中实现了一个shell,而且我很难将命令的输出重定向到文件。 当我将输出发送到文件时,它似乎可以工作,但文件无法打开,当我运行ls -l时,它显示以下内容:

---------x   1 warp  staff   441 Nov  4 20:15 output.txt

这是我的代码的一部分

pid = fork();
if(pid == 0) 
{ /* child process */

    if(redirFlag)
    {
        int fdRedir = open(redirectName, O_WRONLY | O_CREAT );
        if( fdRedir < 0){
            perror("Can't Open");
            exit(1);
        }

        if(dup2(fdRedir, STDOUT_FILENO) == -1){
            perror("dup2 failed");
            exit(1);
        }


    } 
    execvp(supplement[0], supplement);
    /* return only when exec fails */
    perror("exec failed");
    exit(-1);

open的原型是:

#include <fcntl.h>  
int open(const char *path, int oflag, ...);

创建文件后,应指定文件模式。

int open(const char *path, int oflags, mode_t mode);

在您的代码中,文件打开时带有标志O_CREAT但未提供文件模式。 因此,您无权对其进行操作。 尝试在创建新文件时指示文件许可权:

int fdRedir = open(redirectName, O_WRONLY | O_CREAT, 0644);

暂无
暂无

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

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