C file descriptors are copied without sharing offsets or flags

C file descriptors are copied without sharing offsets or flags … here is a solution to the problem.

C file descriptors are copied without sharing offsets or flags

I need to use C to read concurrently from files with different offsets.
The dup unfortunately creates a file descriptor with an offset and flag to the original file share.

Is there a function like dup that doesn’t share offsets and flags?

EDIT I can only access the file pointer FILE* fp; I don’t have a file path

Edit In addition to Mac and many Linux versions, this program is compiled for Windows

Solution
We can use Pread on POSIX systems, and I wrote a pread function for Windows to solve this problem
https://github.com/Storj/libstorj/blob/master/src/utils.c#L227

Solution

On Linux, you can recover the filename from /proc/self/fd/N, where N is the integer value of the file descriptor:

sprintf( linkname, "/proc/self/fd/%d", fd );

Then use readlink() on the generated link name.

If the file has been renamed or deleted, you may be out of luck.

But why do you need another file descriptor? You can use pread() and/or pwrite() on the original file descriptor to read/write the file without affecting the current offset. (Warning: on Linux, pwrite() to a file opened in append mode is wrong – POSIX stipulates that pwrite() to a file opened in append mode will be written to the offset specified in the pwrite() call, but the Linux pwrite() implementation is broken.) The offset is ignored and the data is appended to the end of the file – see the BUGS section of the Linux man page).

Related Problems and Solutions