简单文件 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 适用于简单场景。
相关推荐
技术净胜1 小时前
MATLAB文本文件读写实操fopen/fscanf/fprintf/fclose全解析
开发语言·matlab
Hcoco_me2 小时前
大模型面试题15:DBSCAN聚类算法:步骤、缺陷及改进方向
算法·数据挖掘·聚类
编织幻境的妖2 小时前
Python垃圾回收机制详解
开发语言·python
BrianGriffin2 小时前
JS異步:setTimeout包裝為sleep
开发语言·javascript·ecmascript
遇印记2 小时前
javaOCA考点(基础)
java·开发语言·青少年编程
AI绘画哇哒哒2 小时前
AI 智能体长期记忆系统架构设计与落地实践
人工智能·学习·算法·ai·程序员·产品经理·转行
加藤不太惠2 小时前
【无标题】
java·数据结构·算法
学困昇2 小时前
Linux基础开发工具(下):调试器gdb/cgdb的使用详解
linux·运维·服务器·开发语言·c++
金色旭光2 小时前
目标追踪算法+卡尔曼滤波原理+ByteTrack使用
算法