🔴 短读:转着圈读,读够为止
(本条路线统一用 gcc -std=c11 -O0 -Wall 编译)⚠️ 这一节用 POSIX 的 open/read/write,在 -std=c11 下**必须**先写一行 #define _POSIX_C_SOURCE 200809L,而且要写在所有 #include 前面。
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
/* read 一次不一定读满,要转着圈读到够为止 —— 这就是"短读" */
static ssize_t read_all(int fd, char *buf, size_t want) {
size_t got = 0;
int rounds = 0;
while (got < want) {
ssize_t n = read(fd, buf + got, want - got);
rounds++;
if (n <= 0) break;
got += (size_t)n;
}
(void)rounds;
return (ssize_t)got;
}
int main(void) {
char path[] = "/tmp/l6XXXXXX";
int fd = mkstemp(path);
if (fd < 0) { printf("建不出\n"); return 1; }
const char *msg = "abcdefghij"; /* 10 个字节 */
write(fd, msg, strlen(msg));
lseek(fd, 0, SEEK_SET);
char buf[32] = {0};
ssize_t got = read_all(fd, buf, 10);
close(fd);
unlink(path);
printf("%ld/%d\n", (long)got, strcmp(buf, msg) == 0);
return 0;
}
全部评论