我在 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/