How can a file contain null bytes?

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

    Null-terminated strings are certainly not the only thing that you can put into a file. Operating system code does not consider a file to be a vehicle for storing null-terminated strings: an operating system presents a file as a collection of arbitrary bytes.

    As far as C is concerned, I/O APIs exist for writing files in binary mode. Here is an example:

    char buffer[] = {0, 1, 0, 2, 0, 3, 0, 4, 0, 5};
    FILE *f = fopen("data.bin","wb");  // "w" is for write, "b" is for binary
    fwrite(buffer, 1, sizeof(buffer), f);
    

    This C code creates a file called "data.bin", and writes ten bytes into it. Note that although buffer is a character array, it is not a null-terminated string.

提交回复
热议问题