When I do a fopen and then a fread, when is the file actually/partially loaded in the memory during fopen or fread?
Or is it partially loaded at fopen based on size of file and then fully loaded at time of fread?
Similarly what happens internally at the OS level when fwrite is called? Is the file loaded into memory at that time, or a page swap happens retriving just that part of file in memory?
What happens at the OS level at each of these calls with respect to file loading in memory?
If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.
With fread, yes, you have to allocate memory in your process and the system call will copy the data into your buffer. In some specialised cases, you can handle data without copying it into userspace.
fread() is part of the C library, and provides buffered reads.
fopen()
only creates a handle to the file.fread()
actually reads the file into a memory buffer (OS-level buffering may occur transparently to the client.)fwrite()
writes data into the file, though its committing to the storage may get delayed (e.g. with journalled filesystem.)Typically, the file is not loaded into memory upon opening it. Instead, parts are loaded in for each read; due to all kinds of buffering, greater chunks may be loaded then you ask for in each fread
.
When you fwrite
some data, it is eventually copied into the kernel which will then write it to disk (or wherever) after buffering. In general, no part of a file needs to be loaded in order to write.
Generally it depends on the file system and OS. in windows there is a caching mechanism which deals with a file in 256KB chunks and loads each chunk upon read request falling in that chunk. A call to fopen
should not cause reading the file content from media. And fread
will cause partial read (or complete read for small files) from the media. Partial read usually is equal to cache line size in cache manager (256KB).
fwrite
also may/may not cause a actual write to the media. It usually causes client data to be transferred to the cached file area in RAM, but there is no guaranty that data actually is written to media. in Windows, cache manager decides when to flush a cached area of a file to media. If you want to make sure all dirty data is flushed to media after fwrite
, you need to call fflush
afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With