内存流和null字节

 1 #include <stdio.h>
 2 #include <string.h>
 3 int main()
 4 {
 5     char buf[128]={0};
 6     FILE* fp = fmemopen(buf,128,"w+");
 7     fprintf(fp,"hello world!");
 8     printf("before:%s
",buf);
 9     fflush(fp);
10     printf("after:%s
",buf);
11     printf("len=%d
",strlen(buf));
12 
13     memset(buf,'b',128);
14     fprintf(fp,"hello world!");
15     fseek(fp,0,SEEK_SET);
16     printf("after:%s
",buf);
17     printf("len=%d
",strlen(buf));
18 
19     memset(buf,'c',128);
20     fprintf(fp,"hello world!!");
21     fclose(fp);
22     printf("after close:%s
",buf);
23     printf("len=%d
",strlen(buf));
24 }

这样的一段代码输出:

$main

before:
after:hello world!
len=12
after:bbbbbbbbbbbbhello world!
len=24
after close:hello world!!ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc(���y�
len=136

百思不得其解,百度了一下原来对这段代码困惑的不只是我。

翻了英文版才恍然大悟。

首先对于内存流有这样的规则:

   If the buffer contains no null bytes, then the current position is set to one byte past the end of the buffer。因此15行+19行虽然偏移量变成了0,但是数据量确是是增加了。

   Third, a null byte is written at the current position in the stream whenever we increase the amount of data in the stream’s buffer and call fclose, fflush, fseek, fseeko,orfsetpos.

  中间是and所以要同时满足这两个条件才会增加一个null字节。20行执行的时候流缓冲的数据量相对之前的状态显然是变小了。所以最后一段代码并不会增加一个null字节。

 

原文地址:https://www.cnblogs.com/ittinybird/p/4483329.html