C++文件I/O完全指南:fstream读写、打开模式、定位指针与完整实例
前文使用iostream的cin/cout处理标准输入输出。文件读写需fstream库,定义三类流类型:
| 序号 | 类型与说明 |
|---|---|
| 1 | ofstream 输出文件流:创建文件、写入数据。 |
| 2 | ifstream 输入文件流:读取文件数据。 |
| 3 | fstream 双向文件流:兼具ofstream/ifstream能力,可读可写可创建。 |
需包含<iostream>和<fstream>头文件。
打开文件
读写前必须打开。ofstream/fstream可写,ifstream仅读。标准语法:
void open(const char *filename, ios::openmode mode);
mode常用标志(可按位或|组合):
| 序号 | 模式标志与说明 |
|---|---|
| 1 |
追加模式:所有输出追加至文件末尾。 |
| 2 |
打开后定位至文件末尾(可读可写)。 |
| 3 |
读模式。 |
| 4 |
写模式。 |
| 5 |
文件存在则截断(清空内容)。 |
组合示例:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc); // 写+截断
fstream afile;
afile.open("file.dat", ios::out | ios::in); // 读写
关闭文件
程序结束自动刷新/关闭,但良好习惯显式关闭:void close();
写入文件
用流插入运算符<<,对象为ofstream/fstream而非cout。
读取文件
用流提取运算符>>,对象为ifstream/fstream而非cin。
完整读写示例
#include <fstream>
#include <iostream>
using namespace std;
int main() {
char data[100];
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore(); // 清理换行残留
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data; cout << data << endl;
infile >> data; cout << data << endl;
infile.close();
return 0;
}
样例交互:
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
用getline()读整行,ignore()清理残留字符。
文件定位指针
istream/ostream提供重定位成员函数:
seekg(seek get):输入流定位seekp(seek put):输出流定位
参数为长整型偏移量,第二参数指定基准:ios::beg(默认,文件头)、ios::cur(当前位置)、ios::end(文件尾)。示例:
fileObject.seekg(n); // 定位到第n字节(从头)
fileObject.seekg(n, ios::cur); // 从当前位置前进n字节
fileObject.seekg(n, ios::end); // 从文件尾倒退n字节
fileObject.seekg(0, ios::end); // 定位到文件尾
C语言
- 平锉刀:木工金属加工必备修整工具全解析
- C++结构体与类:嵌入式开发者实战指南
- 掌握 C++ 变量、字面量与常量:核心概念与实战指南
- C++类与对象:面向对象编程实战指南
- C++ 动态内存管理:new 与 delete 专家级实战指南
- C++ 三种继承方式深度解析:public、protected 与 private
- C++ 友元函数与友元类:突破访问控制的利器
- C语言文件处理完全指南:fopen、fprintf、fread 与 fseek
- C 语言头文件详解:类型、用法与最佳实践
- C++日期时间完全指南:ctime库、tm结构体与格式化输出
- C++重载机制深度解析:函数重载与运算符重载全攻略
- 精通 Python 目录与文件操作