Create a file descriptor
Asked Answered
S

2

5

I want to create a file descriptor in C whose value i will specify in code. I have a integer variable which specifies the value of file descriptor to be created. For example i may need a file descriptor whose value is 5 and later associate that with the file named "sample.dat" .

Spendthrift answered 9/5, 2011 at 10:55 Comment(0)
U
6

fd = open ("sample.dat", O_RDONLY); open the file

dup2 (fd, 5); and copy the file descriptor fd into the descriptor number 5

now you can do read (5, buffer, BUFF_MAX); or also use fd to access the same file. You need to close the fd explicitly if you do not need it.

As @Arkadiy told see man dup2 for details.

Unicameral answered 9/5, 2011 at 11:18 Comment(3)
dup and dup2 don't close the old file descriptor.Goldofpleasure
@Chris Lutz: Thanks for pointing it out. I have corrected the error.Unicameral
@ChrisLutz From [LDP] (tldp.org/LDP/lpg/node11.html): NOTES: the old descriptor is closed with dup2()!, please clarify.Variorum
A
4

You need dup2()

http://linux.die.net/man/2/dup

Accost answered 9/5, 2011 at 10:58 Comment(1)
You have to be careful. If newfd already belongs to a file it is closed! I think you would be better of using something like a map.Pendley

© 2022 - 2024 — McMap. All rights reserved.