fmemopen的用法

时间:2019-03-07 02:34:55

标签: c linux stream

我不了解 APUE

fmemopen的示例
#include <stdio.h>
#include <string.h>

#define BSZ 48

int
main()
{
    FILE *fp;
    char buf[BSZ];

    memset(buf, 'a', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    if ((fp = fmemopen(buf, BSZ, "w+")) == NULL)  //"w+" truncate the file by setting the first byte to null byte
        printf("fmemopen failed\n");
    printf("initial buffer contents: %s\n", buf); //print nothing cause the first byte is null byte.
    fprintf(fp, "hello, world"); //write format string to the stream, so the buffer should change and be rewritten.
    printf("before flush: %s\n", buf); //should print "hello, world". Why not?
    fflush(fp);
    printf("after fflush: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    memset(buf, 'b', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    fprintf(fp, "hello, world");
    fseek(fp, 0, SEEK_SET);
    printf("after  fseek: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    memset(buf, 'c', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    fprintf(fp, "hello, world");
    fclose(fp);
    printf("after fclose: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    return(0);
}

我使用Clion进行调试,当它完成fprintf(fp, "hello, world");并到达printf("before flush: %s\n", buf);时,我发现字符数组buf的内容没有改变并且什么也不打印。为什么!?

用于更好描述的调试屏幕截图:

enter image description here

还引用了这本书:

  

第三,每当我们在流中的当前位置写入一个空字节   增加流缓冲区中的数据量,然后调用fclosefflushfseek,   fseekofsetpos

这是什么意思?


更新:

从书中看来,缓冲区在刷新流之前是不变的是预期的结果。

enter image description here

1 个答案:

答案 0 :(得分:-2)

更改堆栈中分配的buf数组

char buf[BSZ];

对此

char* buf = new(std::nothrow) chr[BSZ];

并在关闭流后释放buf

删除[] buf

然后再次测试。