You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中write()后调用read()无法读取刚写入内容的问题

解决C语言write()后read()返回0的问题

问题出在文件偏移指针的位置上:当你调用write()写完数据后,文件指针会停在写入内容的最后一个字节后面。这时候直接调用read(),会从当前指针位置开始读取——而此时已经到了文件末尾,所以read()返回0(表示到达EOF)。虽然文件里确实有"Hallo",但读取位置不对,自然读不到内容。

两种可行的解决方法

  • 方法1:写完后关闭文件,重新打开读取
    关闭文件会重置文件指针,重新打开后指针默认指向文件开头,这时候再调用read()就能读到内容。

  • 方法2:用lseek()手动移动文件指针到开头
    写入完成后,调用lseek(fd, 0, SEEK_SET)将文件指针移回文件起始位置,无需关闭重开。

修正后的代码示例(使用lseek的方式)

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

int main() {
    // 以读写模式打开文件,不存在则创建
    int fd = open("test.txt", O_RDWR | O_CREAT, 0644);
    if (fd == -1) {
        perror("open failed");
        return 1;
    }

    char buf[100] = {0};
    printf("初始缓冲区:%s\n", buf);

    const char *msg = "Hallo";
    ssize_t write_len = write(fd, msg, strlen(msg));
    if (write_len == -1) {
        perror("write failed");
        close(fd);
        return 1;
    }

    // 关键操作:将文件指针移到文件开头
    if (lseek(fd, 0, SEEK_SET) == -1) {
        perror("lseek failed");
        close(fd);
        return 1;
    }

    ssize_t read_len = read(fd, buf, sizeof(buf)-1);
    if (read_len == -1) {
        perror("read failed");
        close(fd);
        return 1;
    }
    buf[read_len] = '\0'; // 手动添加字符串终止符,避免乱码

    printf("读取字符数:%zd\n", read_len);
    printf("读取到的内容:%s\n", buf);

    close(fd);
    return 0;
}

额外注意事项

  • 不要用O_APPEND模式打开文件,这个模式会强制write()时把指针移到末尾,会干扰后续的读取操作。
  • 所有系统调用(open/write/lseek/read)都要检查返回值,一旦出错用perror()打印错误信息,方便排查问题。
  • read()不会自动给缓冲区添加字符串终止符,所以读完后要手动加上'\0',否则打印时可能出现乱码。

内容的提问来源于stack exchange,提问作者Jojo_aka_Hansen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 09:23:22