I would like to have a FILE*
type to use fprintf
.
I need to use fdopen
to get a FILE*
instead of open
that returns an int
.
But can we do the same with fdopen
and open
? (I never used fdopen
)
I would like to do a fdopen
that does the same as :
open("my_file", 0_CREAT | O_RDWR | O_TRUNC, 0644);
If fdopen() returns NULL, use close() to close the file. If fdopen() is successful, you must use fclose() to close the stream and file.
The open function creates and returns a new file descriptor for the file named by filename . Initially, the file position indicator for the file is at the beginning of the file.
fcntl(fd, F_GETFD) is the canonical cheapest way to check that fd is a valid open file descriptor. If you need to batch-check a lot, using poll with a zero timeout and the events member set to 0 and checking for POLLNVAL in revents after it returns is more efficient.
So first unused file descriptor is 3 in file descriptor table. After that in close() system call is free it this 3 file descriptor and then after set 3 file descriptor as null. So when we called second open(), then first unused fd is also 3.
fdopen
takes a file descriptor that could be previously returned by open
, so that is not a problem.
Just open
your file getting the descriptor, and then fdopen
that descriptor.
fdopen
simply creates a userspace-buffered stream, taking any kind of descriptor that supports the read
and write
operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With