fmemopen的用法

问题描述 投票:1回答:1

我听不懂APUEfmemopen的示例]

#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);时,我看到char数组buf的内容不变,什么也不打印

。为什么!?

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

enter image description here

也从书中引用:

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

这是什么意思?


更新:

从书中看来,缓冲区将保持不变,直到刷新流为止

是预期的结果。

enter image description here

我不了解APUE #include #include #define BSZ 48 int main(){文件* fp; char buf [BSZ]; memset(buf,'a',BSZ-2); ...

c linux stream
1个回答
0
投票

更改堆栈中分配的buf数组char buf [BSZ];对此char * buf = new(std :: nothrow)chr [BSZ];并在关闭流delete [] buf后释放了buf然后再次测试。

© www.soinside.com 2019 - 2024. All rights reserved.