简单文件 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 适用于简单场景。
相关推荐
网域小星球3 分钟前
C 语言从 0 入门(十二)|指针与数组:数组名本质、指针遍历数组
c语言·算法·指针·数组·指针遍历数组
tod1136 分钟前
深入解析ext2文件系统架构
linux·服务器·c++·文件系统·ext
不想写代码的星星9 分钟前
C++ 类型萃取:重生之我在幼儿园修炼类型学
c++
比昨天多敲两行10 分钟前
C++11新特性
开发语言·c++
冰糖拌面14 分钟前
二叉树遍历-递归、迭代、Morris
算法
xiaoye-duck24 分钟前
【C++:C++11】核心特性实战:详解C++11列表初始化、右值引用与移动语义
开发语言·c++·c++11
睡一觉就好了。31 分钟前
二叉搜索树
c++
希望永不加班38 分钟前
SpringBoot 事件机制:ApplicationEvent 与监听器
java·开发语言·spring boot·后端·spring
碧海银沙音频科技研究院39 分钟前
虚拟机ubuntu与windows共享文件夹(Samba共享)解决WSL加载SI工程满卡问题
人工智能·深度学习·算法
whitelbwwww39 分钟前
C++进阶--类和模板
c++