gpt4 book ai didi

c - 为什么如果我重定向文件上的 STD_OUT 并写入 STD_OUT 文件仍然为空?

转载 作者:行者123 更新时间:2023-12-04 13:10:30 25 4
gpt4 key购买 nike

我无法用标准输出解决问题 笑,我在 Unix 操作系统上,所以 STD_IN = 0,STD_OUT = 1,STD_ERR = 2 的文件描述符,基本上我试图关闭与标准输出,然后用我要写入的文件覆盖它,但是当我打开文件时它是空的。代码:

#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
/*special file's descriptor --use it or constants in unistd.h-- */
#define STD_IN 0 /*standard input stream*/
#define STD_OUT 1 /*standard output stream*/
#define STD_ERR 2 /*standard output-error stream*/

int main(unsigned int num_of_args, char** args)
{
if(num_of_args != 3)
{
write(STD_ERR, "Few argouments.\nThe use = ./executable <message> <file>\n", 69);
return -1;
}

int file_des= open(args[2], O_CREAT, 0640);

if(file_des < 0)
{
write(STD_ERR, "Error, we couldn't open file.\n", 31);
return -1;
}

//I close the descriptor associated with STD_OUT
close(STD_OUT);

//I copy the descriptor associated with fil_des on the first available descriptor(so STD_OUT)
dup(file_des);

write(STD_OUT, args[1], sizeof(args[1]));

close(file_des);

return 0;
}

应该没问题,我没有看到任何错误,但是当我打开文件时,我没有找到写入的消息。因为?帮帮我

最佳答案

此代码不正确:

int file_des= open(args[2],  O_CREAT,  0640);

根据 the POSIX documentation for open() (注意粗体部分 - 我的粗体):

SYNOPSIS

#include <sys/stat.h>
#include <fcntl.h>

int open(const char *path, int oflag, ...);
int openat(int fd, const char *path, int oflag, ...);

DESCRIPTION ...

Values for oflag are constructed by a bitwise-inclusive OR of flagsfrom the following list, defined in <fcntl.h>. Applications shallspecify exactly one of the first five values (file access modes) belowin the value of oflag:

O_EXEC
Open for execute only (non-directory files). The result is unspecified if this flag is applied to a directory.
O_RDONLY
Open for reading only.
O_RDWR
Open for reading and writing. The result is undefined if this flag is applied to a FIFO.
O_SEARCH
Open directory for search only. The result is unspecified if this flag is applied to a non-directory file.
O_WRONLY
Open for writing only.

你的 open()电话需要包括 O_WRONLYO_RDWR当您写入文件时:

int file_des= open(args[2],  O_CREAT | O_WRONLY,  0640);

关于c - 为什么如果我重定向文件上的 STD_OUT 并写入 STD_OUT 文件仍然为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66027778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com