How can a file contain null bytes?

前端 未结 6 1951
一整个雨季
一整个雨季 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:50

    Consider the usual C function calls for writing data to files — write(2):

    ssize_t
    write(int fildes, const void *buf, size_t nbyte);
    

    … and fwrite(3):

    size_t
    fwrite(const void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);
    

    Neither of these functions accept a const char * NUL-terminated string. Rather, they take an array of bytes (a const void *) with an explicit size. These functions treat NUL bytes just like any other byte value.

提交回复
热议问题