The following code is expected to write “some text” to demo.txt, but it doesn’t work:
#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;
}
You should use
fflush(fp)to clear the buffer before closing the file.When you write to the file descriptor
fp, the data is buffered.But you are closing the file with
close(fd)before the buffered data can be written written to the filedemo.txt. Hence, buffered data is lost.If you do
fflush(fp), it will ensure the buffered data is written to demo.txt immediately.You should not call
close()before doingfclose()for all the opened files.Proper way is to do
fclose(fp)first and then doclose(fd).