zoukankan      html  css  js  c++  java
  • 内存流和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字节。

     

  • 相关阅读:
    Bootstrap 2.3.2导航问题
    隐藏wordpress登陆后台
    WordPress 中文图片 上传 自动重命名
    wordpress上传附件提示抱歉,出于安全的考虑,不支持此文件类型
    移动端适配
    项目中常见的正则校验
    vue中 的 this.$nextTick (Vue中DOM的异步更新)
    vue中使用webscoket
    登堂入室---进阶代码
    Flex布局
  • 原文地址:https://www.cnblogs.com/ittinybird/p/4483329.html
Copyright © 2011-2022 走看看