简单文件 IO 示例:使用系统调用读写文件

这是一个基础的文件 IO 示例,使用 Linux 系统调用处理 "data.txt" 文件。代码基于文件描述符(fd),演示写入和读取操作,包含错误处理宏。read/write 是阻塞的同步 IO,适合理解底层机制。

示例 1: 文件写入程序

程序创建或覆盖文件,写入固定字符串。

复制代码
#include <iostream>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>

// 错误处理宏
#define error_handling(message) { std::cerr << message << "error!" << strerror(errno) << std::endl; exit(1); }

int main() {
    int fd;
    std::string buf = "hello,world!\n";
    /*
    O_CREAT     必要时创建文件
    O_TRUNC     删除全部现有数据
    O_APPEND    维持现有数据,保存到其后面
    O_RDONLY    只读打开
    O_WRONLY    只写打开
    O_RDWR      读写打开
    */
    fd = open("data.txt", O_CREAT | O_WRONLY | O_TRUNC);  // 创建/覆盖,只写模式
    if (fd == -1) error_handling("open");
    if (write(fd, &buf[0], buf.size()) == -1) error_handling("wrote");  // 写入数据
    close(fd);
    return 0;
}
  • 关键点open 以 O_CREAT|O_WRONLY|O_TRUNC 模式打开文件(创建、清空、只写);write 将字符串数据写入 fd。

示例 2: 文件读取程序

程序读取文件内容并打印。

复制代码
#include <iostream>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>

// 错误处理宏
#define error_handling(message) { std::cerr << message << "error!" << strerror(errno) << std::endl; exit(1); }

int main() {
    int fd;
    std::string buf;
    buf.resize(BUFSIZ);  // 分配缓冲
    fd = open("data.txt", O_RDONLY);  // 只读模式打开
    if (fd == -1) error_handling("open");
    std::cout << "file descriptor: " << fd << std::endl;
    if (read(fd, &buf[0], buf.size()) == -1) error_handling("read");  // 读取数据
    std::cout << "file data: " << buf << std::endl;
    close(fd);
    return 0;
}
  • 关键点open 以 O_RDONLY 模式打开;read 从 fd 读取到 std::string 缓冲区(BUFSIZ 为标准大小);输出 fd 和内容。

流程概述

  • 写入:open → write → close。
  • 读取:open → read → close。
  • 底层:系统调用确保数据持久化,阻塞式 IO 适用于简单场景。
相关推荐
Lhan.zzZ31 分钟前
笔记_2026.4.28_004
c++·ide·笔记·qt
MATLAB代码顾问1 小时前
5大智能算法优化标准测试函数对比(Python实现)
开发语言·python
wuminyu2 小时前
专家视角看Java字节码加载与存储指令机制
java·linux·c语言·jvm·c++
万粉变现经纪人2 小时前
如何解决 pip install llama-cpp-python 报错 未安装 CMake/Ninja 或 CPU 不支持 AVX 问题
开发语言·python·开源·aigc·pip·ai写作·llama
清风明月一壶酒3 小时前
OpenClaw自动处理Word文档全流程
开发语言·c#·word
其实防守也摸鱼3 小时前
CTF密码学综合教学指南--第五章
开发语言·网络·笔记·python·安全·网络安全·密码学
木喃的井盖3 小时前
无锁队列细节
c++·工程
王老师青少年编程3 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串基础】:输出亲朋字符串
c++·字符串·csp·高频考点·信奥赛·专项训练·输出亲朋字符串
MediaTea3 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z4 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode