Search code examples
cmacosfilestreamfile-descriptor

Do FILE * continue to work if the fd linked to them is used for some other purpose?


I have generally worked only with file descriptors. I am not sure if a FILE * will continue to work correctly if the fd linked to it is used for someother purpose. Do FILE * and fd linked to it exist independently?


Solution

  • On POSIX systems, yes, the fd backs the FILE*. Closing the FILE* closes the fd. Interleaving use the fd and FILE* risks mucking up your data (the FILE* does user mode buffering that the fd bypasses); you'd have to either disable buffering (with setvbuf or the like) or make sure the FILE* is reliably flushed before anything writes to the fd directly. Otherwise, as long as nothing closes the fd, the FILE* should continue to work.