如有错误,欢迎批评指正,本人也是才学APUE的菜鸟
先贴上代码:
#include "apue.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)
err_sys("fmemopen failed");
printf("initial buffer contents: %s\n", buf);
fprintf(fp, "hello, world");
printf("before flush: %s\n", buf);
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));
// 下面的 fclose 并没有追加 null 字节。
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));
// 但是这种方式的 fclose 会追加 null 字节。
/*
memset(buf, 'c', BSZ - 2);
buf[BSZ - 2] = '\0';
buf[BSZ - 1] = 'X';
fprintf(fp, "hello, Peter! how are you?");
fclose(fp);
printf("after fclose: %s\n", buf);
printf("len of string in buf = %ld\n", (long) strlen(buf));
*/
return 0;
}
首先,程序的输出是这样的:
initial buffer contents:
before flush:
after fflush: hello, world
len of string in buf = 12
after fseek: bbbbbbbbbbbbhello, world
len of string in buf = 24
after fclose: hello, worldcccccccccccccccccccccccccccccccccc
len of string in buf = 46
要理解为什么会是这样的输出。需要做的就是时刻关注当前的文件位置。
以及 APUE 上的那一句话:任何时候需要增加缓冲区中数据量以及调用 fclose、fflush、fseek、fseeko 以及 fsetpos 时,都会在当前位置写入一个 null 字节。
- 起初:虽然执行了 memset(buf, ‘a’, BSZ - 2),但执行 fmemopen 时,流的控制参数为 “w+”,所以会在缓冲区开始处放置 null 字节。所以第一个输出为 空;
- 接着调用了 fprintf,向 fp 中写入 “hello, world”,但我们都知道,再调用了 fflush 冲洗流之后,它才写到 buf,而且,会在 “hello, world” 之后加上 null 字节,所以也就有第二三四个输出。
- 注意:此时的文件位置为 12 (指向 null)
- memset(buf, ‘b’, BSZ - 2),然后写入 “hello, world”,这里的 “hello, word” 就是从下标 12 的位置开始写入的了。fseek 会导致再追加一个 null 字节,同时会冲洗流。所以会有 after seek 这样的输出。然后将文件位置置为 0。
- memset(buf, ‘c’, BSZ - 2),然后写入 “hello, world”,此时的文件位置为 0,所以 “hello, world” 是从头还是写的。但这里并未引起追加 null 字节,所以会有 after close: 这样的输出。
/
/
我一直再纠结,到底什么情况下才是引起了缓冲区中数据量增加,所以我把第三种方式换成了代码中的注释部分。得到以下输出:
initial buffer contents:
before flush:
after fflush: hello, world
len of string in buf = 12
after fseek: bbbbbbbbbbbbhello, world
len of string in buf = 24
after fclose: hello, Peter! how are you?
len of string in buf = 26
发现第三次写入的 “hello, Peter! how are you?” 长度大于上一个输出的 buf = 24,这种情况下就追加了 null 字节。
所以我猜测:当,当前文件位置 + 写入的长度 >= 上一次的 null 位置时,便叫做 引起了缓冲区中数据量增加。同时,null 的位置只可能越来越大的。
/
/