我无法解决标准输出的问题,我的操作系统是Unix。在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;
}
应该没问题,我没有看到任何错误,但是当我打开文件时,我找不到写的消息。为什么?帮帮我。
#define STD_IN 0
?POSIX已经在unistd.h
中定义了STDIN_FILENO
,STDOUT_FILENO
和STDERR_FILENO
。 - Andrew HenleSTDOUT_FILENO
或者1
被close()
关闭了,那么可用的最小编号文件描述符将会是1
。在这种情况下,dup()
保证返回1
:"除非另有规定,否则打开一个或多个文件描述符的所有函数都应在每次分配时原子地分配调用进程中尚未打开的最低编号可用文件描述符。" - Andrew Henle