写进去几个,读回来几个(系统调用版)

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

(本条路线统一用 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>

int main(void) {
    /* mkstemp 建一个名字由系统给的文件,并直接给你 fd */
    char path[] = "/tmp/l6XXXXXX";
    int fd = mkstemp(path);
    if (fd < 0) { printf("建不出\n"); return 1; }

    const char *msg = "hello";
    ssize_t w = write(fd, msg, strlen(msg));

    lseek(fd, 0, SEEK_SET);
    char buf[16] = {0};
    ssize_t r = read(fd, buf, sizeof(buf) - 1);

    close(fd);
    unlink(path);

    /* fd 的具体数字不能当答案,只能问它有没有拿到 */
    printf("%ld/%ld/%d\n", (long)w, (long)r, strcmp(buf, msg) == 0);
    return 0;
}
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论