>以下是我使用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
}
_O_RDWR必须被OR放入_open的第二个参数中。