我想处理
write
:为什么它不写入文件(errno 9,EBADF: Bad file descriptor
),尽管如果你用fdOut
替换1
,那么一切都会完美地显示在屏幕上?
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main (void)
{
int fdOut;
char *outFileName = "out";
char sample[7] ="sample\0";
fdOut = open (outFileName, O_CREAT, 0777);
if (fdOut == -1)
printf ("ups, errno %d\n", errno);
else
{
write (fdOut, sample, 7);
write (fdOut, "\n", 1);
}
close (fdOut);
printf ("%s", sample);
return (0);
}
查看
open
的文档(例如 here),我们看到:
参数flags必须包含以下访问模式之一:
、O_RDONLY
或O_WRONLY
。这些请求分别以只读、只写或读/写方式打开文件。O_RDWR
在这种情况下,可以安全地假设您想要
O_WRONLY
:
fdOut = open (outFileName, O_CREAT | O_WRONLY, 0777);
您可能还想查看
O_TRUNC
以了解该文件确实存在的情况。