Reputation: 41017
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;
}
Upvotes: 0
Views: 5559
Reputation: 13356
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 file demo.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 doing fclose()
for all the opened files.
Proper way is to do fclose(fp)
first and then do close(fd)
.
Upvotes: 2
Reputation: 51832
The mode flag passed to fdopen()
must be compatible with the mode of the file descriptor. The file descriptor's mode is O_RDWR
, but you're doing:
fp = fdopen(fd, "w");
That might not work (it's undefined behavior.) Instead, open in "r+"
mode:
fp = fdopen(fd, "r+");
Alternatively, use O_WRONLY
for the file descriptor:
open("demo.txt", O_WRONLY)
Then you can fdopen()
in "w"
mode.
Finally, close the FILE
structure instead of closing the file descriptor:
fclose(fp);
If you don't do that, fp
loses its underlying file descriptor. You must not try to close the file descriptor manually after that. fclose()
does that on its own.
Upvotes: 2