How files are saved?
Can anyone here tell me how files are usually saved in hard disk? Is the contents are represented using binary value i.e in 1's and 0's. I开发者_C百科f so, is it possible to print those 1's & 0's using C program?
Yes, in the lowest level the contents of all files are binary bits and bytes. You can read these if you open the file for reading in binary mode:
FILE * pFile;
pFile = fopen ("somefile.txt","rb");
...
You can then read from the file into a byte buffer using fread
, and print out the bytes read in the desired format (like "%x"
for hexadecimal) using printf
.
how files are usually saved in hard disk?
How files are stored depends on the underlying filesystem.
Is the contents are represented using binary value i.e in 1's and 0's.
At the very end, everything on your pc are represented by 0 and 1, so even files, yes.
The C programming language creates an abstraction that files are streams of bytes. As far as C is concerned, a byte consists of a number of bits (1 or 0 values) equal to CHAR_BIT
.
Whether the hardware actually stores a byte in terms of a number of bits is irrelevant to C, since the C implementation (in combination with the OS, etc) will make it look as though it does. If you can design a storage medium with lots of tiny little blobs, each of which can be in any of 256 states, then you're welcome to store 1 byte per blob.
But in fact, both magnetic and flash HDDs do have microscopic structures corresponding to a single bit. The hardware doesn't provide direct access to a single bit, but they are in there. Whether a single bit on the storage medium corresponds to a single bit in the file is another matter -- both the hardware and the filesystem software can perform a series of operations on the data (compression, encryption, RAID duplication, sparse files) that make things a lot more complicated than just "8 bits on disk equals one byte of file".
Sure it is - in Linux, just open /dev/sda1
(or whatever block device you have; this example is for the first partition of the first hard disk) and start reading; similarly in other OSes.
Note that
- you'll need superuser/Administrator permissions for such low-level disk access
- there's usually also the filesystem abstracting away the storage from the files - in other words, a file of 10 MB doesn't necessarily correspond to a single, 10-MB-sized part of the disk: it may be in multiple parts, it may be compressed, or encrypted, or all of those
- with distributed/network/memory filesystems, the file may not actually exist on a disk at all.
Therefore, a file (as it appears when you normally open it) doesn't necessarily look like that on the disk (it could, but there's no guarantee of that, and indeed no point).
精彩评论