![](/img/trans.png)
[英]How to redirecting input into my C program from a file and command line arguments to graph node?
[英]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.