无法使文件描述符_write函数正常工作-Windows 10

时间:2019-01-24 10:56:11

标签: c file-descriptor stdio

下面是我使用VS2017为Windows编写的一些简单代码的两个版本。可通过#if指令选择它们。第一个版本使用文件描述符功能打开文件,然后将其写入。第二个版本使用stdio函数执行相同的操作。这两个版本都成功打开了文件,并在需要时创建了文件,但只有stdio版本成功写入了文件。文件描述符版本失败,并导致出现错误消息“ C:/temp/fdio.txt:错误的文件描述符”。我已经尝试了带有和不带有前导下划线的文件描述符函数和标志,但是结果是相同的。请告诉我我所缺少的。

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

int main(void)
{
   const char *fileName = "C:/temp/fdio.txt";
   char buf[] = "This is a test";

#if 1
   int fd = _open(fileName, _O_CREAT | _O_TRUNC | _O_TEXT, _S_IREAD | _S_IWRITE);
   if (fd == -1)
   {
      perror(fileName);
      exit(1);
   }

   int status = _write(fd, (void *)buf, (unsigned)sizeof(buf));
   if (status == -1)
   {
      perror(fileName);
      exit(1);
   }
#else
   FILE *fp = fopen(fileName, "w+");
   if (!fp)
   {
      perror(fileName);
      exit(1);
   }
   size_t status = fwrite(buf, 1, sizeof(buf), fp);
   if (status != sizeof(buf))
   {
      perror(fileName);
      exit(1);
   }
#endif
}

1 个答案:

答案 0 :(得分:0)

_O_RDWR必须与_open的第二个参数进行或运算。