It is possible to write less than 1 byte to a file

耗尽温柔 提交于 2020-01-12 13:51:23

问题


As far as I know the smallest unit in C is a byte. Where does this constraint comes from? CPU?

For example, how can I write a nibble or a single bit to a file?


回答1:


no, you can't... files are organized in bytes, it's the smallest piece of data you can save.

And, actually, that 1 byte will occupy more than 1 byte of space, in general. Depending on the OS, the system file type, etc, everything you save as a file will use at least one block. And the block's size varies according to the file system you're using. Then, this 1-bit will be written as 1 - byte and can occupy as much as 4kB of your disk.

In wikipedia you can read something about the byte being the smallest data unit in many computers.




回答2:


Actually, it's a char--byte is not a standard C type.

The constraint comes from the C standard and is tautological: char is the smallest complete type in C because it is defined as such, and the sizes of all other types are defined as multiples of the size of char (whose size is always 1.)

Now, the number of bits in a char can vary from platform to platform. The number of bits tends to ultimately be hardware-defined, though most systems these days use 8-bit chars. char is supposed to represent the smallest addressable unit of memory (again, by definition.)




回答3:


Moreover data is written to files in sectors (e.g. 512 bytes or so). And if we need to change only one byte the whole sector is read, patched and written back.

But you don't need to thinkabout sectors. To Change one bit just seek to apropriate byte position in file, read that byte, change the bit and write the result back.



来源:https://stackoverflow.com/questions/6701221/it-is-possible-to-write-less-than-1-byte-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!