我听不懂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);
时,我看到char数组buf
的内容不变,什么也不打印
用于更好描述的调试屏幕截图:
也从书中引用:
第三,每当我们在流中的当前位置写入一个空字节增加流缓冲区中的数据量,然后调用
fclose
,fflush
,fseek
,fseeko
或fsetpos
。这是什么意思?
更新:
从书中看来,缓冲区将保持不变,直到刷新流为止
是预期的结果。我不了解APUE #include
更改堆栈中分配的buf数组char buf [BSZ];对此char * buf = new(std :: nothrow)chr [BSZ];并在关闭流delete [] buf后释放了buf然后再次测试。