这是一个基础的文件 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 适用于简单场景。