【发布时间】: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