What are the main differences between fwrite and write?

I am currently writing a callback function in C :

 static size_t writedata(void *ptr, size_t size, size_t nmemb, void *stream){ size_t written = fwrite(ptr, size, nmemb, (FILE)*stream); return written; } 

This function will be used in another function that executes an HTTP request, retrieves the request, and writes it to the local computer. This writedata function will be used for a later part. The whole operation must be multithreaded , so I doubted between write and fwrite . Can someone help me highlight the differences between write() and fwrite() in C , so I could choose which one works best for my problem?

+8
c ++ c
source share
2 answers

fwrite written to FILE* , i.e. a (potentially) buffered stdio stream. It is defined by the ISO C standard. In addition, in POSIX fwrite systems are somewhat thread safe .

write is a lower-level API based on file descriptors described in the POSIX standard. He does not know about buffering. If you want to use it on FILE* , then select its file descriptor with fileno , but remember to manually block and clear the stream before trying to write .

Use fwrite if you don't know what you are doing.

+16
source share

The write function is a call that your program makes on the operating system, and therefore it is slower than fwrite . It also does not have buffering , which makes it even slower because, as the buffering philosophy states, "it is faster to process many small files, not large ones." It is also important that write not part of the c standard, so you probably won't find it on non-POSIX systems and (rarely) the appropriate use will be different. You should also be aware that fwrite and fread are implemented several times using write and read (a simple implementation can be found in the Unix K & R chapter).

Another noteworthy thing: read and write use file descriptors , but fread and fwrite use FILE pointers, which are actually pointers that contain file descriptors and other information about the file that opens.

+1
source share

All Articles