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

标签 c shell unix command

我在 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的原型(prototype)是:

#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);

关于c - 从命令行将输出重定向到 C 中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19780433/

相关文章:

bash - 如何在 unix 中从当前时间减去 60 分钟

linux - 在 if 条件中使用 bash 算术运算符时结果不正确

C程序——泰勒级数_长公式

对指向字符串的指针数组进行排序时崩溃

c++ - 按时间管理许可证

c - Travis CI 使用非 perl 语言安装 perl 模块

shell_exec 中的 PHP sudo

linux - 在同一子目录中查找具有相同 MD5 的文件

linux - Lynx:当用户名包含域时如何使用 -auth 标志?

linux - 更正 "nice"批处理程序的 POSIX 调度优先级