fmemopen 的用法 [英] Usage of fmemopen
问题描述
我不明白 APUE
#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
的内容没有改变,什么也不打印.为什么!?
I use Clion to debug and when it finishes fprintf(fp, "hello, world");
and comes to printf("before flush: %s\n", buf);
, I see the content of char array buf
does not change and print nothing. Why!?
调试屏幕截图,以便更好地描述:
A debug screenshot for better description:
另外,引用自书中:
第三,每当我们在流中的当前位置写入一个空字节增加流缓冲区中的数据量并调用fclose
、fflush
、fseek
,fseeko
或 fsetpos
.
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
.
这是什么意思?
更新:
从书中看来,缓冲区在刷新流之前保持不变是预期的结果.
From the book and it seems that buffer is unchanged until stream is flushed is the expected result.
推荐答案
改变栈中分配的buf数组
change the allocated buf array in the stack
char buf[BSZ];
到这里
char* buf = new(std::nothrow) chr[BSZ];
并在关闭流后释放 buf
and freed buf after close the stream
删除[]缓冲区
并再次测试.
这篇关于fmemopen 的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!