以下代码将向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 text\n");
close(fd);
return 0;
}发布于 2012-10-31 19:34:06
在关闭文件之前,您应该使用fflush(fp)清除缓冲区。
当您写入文件描述符fp时,数据将被缓冲。但是在将缓冲数据写入文件demo.txt之前,您需要使用close(fd)关闭该文件。因此,缓存的数据会丢失。如果您使用fflush(fp),它将确保缓冲的数据立即写入demo.txt。
您不应该在对所有打开的文件执行fclose()之前调用close()。
正确的方法是先做fclose(fp),然后做close(fd)。
发布于 2012-10-31 19:40:31
传递给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()自己做到了这一点。
发布于 2012-10-31 19:36:14
使用fclose(fp)而不是close(fd)
https://stackoverflow.com/questions/13156902
复制相似问题