试试read(2)(在unistd.h),它应该输出5个字符。使用 libc(fread(3)、fwrite(3) 等)时,您使用的是内部 libc 缓冲区,它通常是一个页面的大小(几乎总是 4 kiB)。
我相信,当您第一次调用 fread() 5 个字节时,libc 会执行 4096 个字节的内部 read(),而下面的 fread() 将简单地返回 libc 在与 FILE 关联的缓冲区中已有的字节你使用的结构。直到达到 4096。第 4097 个字节将发出另一个 4096 字节的 read,依此类推。
这也会在您编写时发生,例如在使用printf() 时,这只是fprintf() 和stdout() 作为它的第一个参数。 libc 不会直接调用write(2),而是将你的东西放在它的内部缓冲区中(也是4096字节)。如果你调用它会刷新
fflush(stdout);
您自己,或任何时候它在发送的字节中找到字节 0x0a(ASCII 中的换行符)。
试试看,你会看到:
#include <stdio.h> /* for printf() */
#include <unistd.h> /* for sleep() */
int main(void) {
printf("the following message won't show up\n");
printf("hello, world!");
sleep(3);
printf("\nuntil now...\n");
return 0;
}
但是这会起作用(不使用 libc 的缓冲):
#include <stdio.h> /* for printf() */
#include <unistd.h> /* for sleep(), write(), and STDOUT_FILENO */
int main(void) {
printf("the following message WILL show up\n");
write(STDOUT_FILENO, "hello!", 6);
sleep(3);
printf("see?\n");
return 0;
}
STDOUT_FILENO 是标准输出 (1) 的默认文件描述符。
每次出现换行符时刷新对于终端用户即时查看消息至关重要,并且对于在 Unix 环境中经常执行的每行处理也很有帮助。
因此,即使 libc 直接使用 read() 和 write() 系统调用来填充和刷新其缓冲区(顺便说一下,C 标准库的 Microsoft 实现必须使用 Windows 的东西,可能是 ReadFile 和 @987654345 @),那些系统调用绝对不知道 libc。当同时使用这两种方法时,这会导致有趣的行为:
#include <stdio.h> /* for printf() */
#include <unistd.h> /* for write() and STDOUT_FILENO */
int main(void) {
printf("1. first message (flushed now)\n");
printf("2. second message (without flushing)");
write(STDOUT_FILENO, "3. third message (flushed now)", 30);
printf("\n");
return 0;
}
哪个输出:
1. first message (flushed now)
3. third message (flushed now)2. second message (without flushing)
(第二个之前的第三个!)。
另外,请注意,您可以使用 setvbuf(3) 关闭 libc 的缓冲。示例:
#include <stdio.h> /* for setvbuf() and printf() */
#include <unistd.h> /* for sleep() */
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
printf("the following message WILL show up\n");
printf("hello!");
sleep(3);
printf("see?\n");
return 0;
}
我从未尝试过,但我想你可以对 FILE* 执行相同的操作,当 fopen() 输入字符设备并为此禁用 I/O 缓冲时:
FILE* fh = fopen("/dev/my-char-device", "rb");
setvbuf(fh, NULL, _IONBF, 0);