I was dealing with a prepending problem and suddenly leads me to think about this question….
Maybe not only related to FileStream, I want to know how we actually appends binary into a file physically work.
I guess my question will leads two quetions:
- How the hard disk memory is structured?
- How file write into physical memory?
Say I have a Text File, contains “ABCDEF”, so in physical memory (in hard disk), the memory should contains the binary of the letters “ABCDEF” with file header binary etc (actually no header for plain text file?)….
So will be something like this in physically 6 bytes, orders depends on the processor type:
A B C D E F 01000001 01000010 01000011 01000100 01000101 01000110
Say when we want to appends a letter ‘G’ in the file, so the file will contains 7 bytes:
A B C D E F G 01000001 01000010 01000011 01000100 01000101 01000110 01000111
Both file size in disk physically should 4.00KB.
Because when we write the letter G, is still not excess the 4.00KB, so we have space to write into the 4.00KB memory space.
But when we will appends more things in the file, when execess the 4.00KB will be using 8.00KB.
How does the binary that excess the 4.00KB write into the disk memory?
Does it write a pointer or something to somewhere and declare an index in the disk memory and write the excessing binary into the new memory address?
Issues like this is why we use OSs, it provides a layer of abstraction so you do not need to concern yourself at the application level about things like how the memory is stored on the hardware level.
The layers are similar to this (for HDD drives), Each layer shows next to it who is responsible for that layer.
File (File system) | v Bitstream (OS) | v Sectors (Hardware Driver) | V Bits (Hard disk controller) | V Magnetic flux (Hard disk controller)
Each layer does not care what the layers above or below it are doing, the only important thing is that it exposes a known API to direct layer above it and it uses a known API to the direct layer below it.
When writing applications you almost never get below the Bitstream layer (
System.IO.Stream) when you write your data to the stream it hands it off to the driver and the driver will split the data however it the next layer below it needs it to be split (4k chunks for modern HDDs).
For how the driver tracks “what goes where?” that is up to the driver’s implementation.
To actually answer your question, Append works by your program requests the Bitstream for a file. Once it has the bitstream it adds more data to the end of the bitstream. What the OS/Driver does to that bitstream once you write to it is a black box (you don’t know the details) and it will be totally different if you are working with a
MemoryStream, or a
NetworkStream. The great thing about this layered structure is you don’t need to care! The responsibility is the next layer down’s and that layer deals with it.