以下代码应将"某些文本"写入demo.txt,但它不起作用:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
FILE *fp;
int fd;
if ((fd = open("demo.txt", O_RDWR)) == -1) {
perror("open");
exit(1);
}
fp = fdopen(fd, "w");
fprintf(fp, "some textn");
close(fd);
return 0;
}
您应该在关闭文件之前使用fflush(fp)
清除缓冲区。
写入文件描述符fp
时,数据将被缓冲。但是,在可以写入文件demo.txt
之前,您将使用close(fd)
关闭文件。因此,缓冲数据丢失了。如果您执行fflush(fp)
,它将确保立即将缓冲数据写入Demo.txt。
为所有打开的文件执行fclose()
之前,您不应致电close()
。
正确的方法是首先执行fclose(fp)
,然后进行close(fd)
。
传递给fdopen()
的模式标志必须与文件描述符的模式兼容。文件描述符的模式是O_RDWR
,但是您正在这样做:
fp = fdopen(fd, "w");
可能行不通的(这是不确定的行为。)相反,以"r+"
模式打开:
fp = fdopen(fd, "r+");
或者,将O_WRONLY
用于文件描述符:
open("demo.txt", O_WRONLY)
然后您可以在"w"
模式下进行fdopen()
。
最后,关闭FILE
结构,而不是关闭文件描述符:
fclose(fp);
如果您不这样做,则fp
失去其基础文件描述符。之后,您不得尝试手动关闭文件描述符。fclose()
自己做。
使用fclose(fp)而不是关闭(fd)