How can a file contain null bytes?

前端 未结 6 1947
一整个雨季
一整个雨季 2021-02-03 23:17

How is it possible that files can contain null bytes in operating systems written in a language with null-terminating strings (namely, C)?

For example, if I run this she

6条回答
  •  我寻月下人不归
    2021-02-03 23:45

    While null-bytes are used to terminate strings and needed for string manipulation functions (so they know where the string ends), in binary files \0 bytes can be everywhere.

    Consider a binary file with 32-bit numbers for example, they will all contain null-bytes if their values are smaller than 2^24 (for example: 0x001a00c7, or 64-bit 0x0000000a00001a4d).

    Idem for Unicode-16 where all ASCII characters have a leading or trailing \0, depending on their endianness, and strings need to end with \0\0.

    A lot of files even have blocks padded (to 4kB or even 64kB) with \0 bytes, to have quick access to the desired blocks.

    For even more null-bytes in a file, take a look at sparse files, where all bytes are \0 by default, and blocks full of null-bytes aren't even stored on disk to save space.

提交回复
热议问题