Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fdopen as open with the same mode and flags?

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);
like image 736
Elfayer Avatar asked Feb 27 '13 11:02

Elfayer


People also ask

How do you close after Fdopen?

If fdopen() returns NULL, use close() to close the file. If fdopen() is successful, you must use fclose() to close the stream and file.

How does open () work in C?

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.

How do I know if a file descriptor is open?

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.

What will be the value of the first file descriptor you will get after opening a new file with open?

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.


1 Answers

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.

like image 198
Blagovest Buyukliev Avatar answered Oct 19 '22 18:10

Blagovest Buyukliev