【问题标题】:Can't get file descriptor _write function to work - Windows 10无法使文件描述符 _write 函数工作 - Windows 10
【发布时间】:2019-01-24 10:56:11
【问题描述】:

以下是我使用 VS2017 为 Windows 编写的一些简单代码的两个版本。它们可以通过#if 指令进行选择。第一个版本使用文件描述符函数打开文件然后写入文件。第二个版本使用 stdio 函数做同样的事情。两个版本都成功打开文件,必要时创建它,但只有 stdio 版本成功写入。文件描述符版本失败并导致错误消息“C:/temp/fdio.txt: Bad file descriptor”。我已经尝试了带和不带前导下划线的文件描述符函数和标志,但结果是相同的。请告诉我我错过了什么。

#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
}

【问题讨论】:

    标签: c file-descriptor stdio


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-03-09
      • 2011-01-14
      • 2023-03-09
      • 2011-10-28
      • 1970-01-01
      • 2016-05-08
      • 2011-10-02
      • 2017-02-12
      相关资源
      最近更新 更多