31

Is there any way to change an int file descriptor to a FILE struct pointer or/and change FILE* to a file descriptor in C?

o11c
  • 15,265
  • 4
  • 50
  • 75
trrrrrrm
  • 11,362
  • 25
  • 85
  • 130

2 Answers2

39

The function fdopen() returns a new (FILE *) associated with an open file descriptor.

The function fileno() returns the file descriptor associated with an open FILE *.

Kamal
  • 7,160
  • 2
  • 21
  • 12
  • 3
    Caveat: `fdopen` takes ownership, whereas `fileno` returns a view. It is very difficult to avoid some of the edge cases even if you use `dup` in conjunction, since `fclose` modifies the underlying file descriptor. – o11c Jun 09 '18 at 16:09
28

Use "fileno()" for FILE->int.

Use "fdopen()" for int->FILE.

user172818
  • 4,518
  • 1
  • 18
  • 20