C++文件操作需包含fstream头文件,使用ofstream写入、ifstream读取、fstream读写文件,支持文本和二进制模式,需检查文件是否打开并选择合适模式。

在C++中进行文件读写操作,主要使用标准库中的 fstream 头文件。它提供了三个核心类:
- ifstream:用于从文件读取数据(input file stream)
- ofstream:用于向文件写入数据(output file stream)
- fstream:同时支持读写操作
下面通过具体示例详细讲解如何使用这些类完成常见的文件操作。
1. 包含头文件
#include#include iostream>
#include
这三个头文件分别用于文件操作、输入输出和字符串处理。
2. 写入文件(ofstream)
使用 ofstream 向文件中写入内容。如果文件不存在会自动创建;如果已存在,默认会覆盖原内容。
立即学习“C++免费学习笔记(深入)”;
std::ofstream file("example.txt");if (file.is_open()) {
file file file.close();
} else {
std::cout }
你也可以以追加模式写入,避免覆盖原内容:
std::ofstream file("example.txt", std::ios::app);file
3. 读取文件(ifstream)
使用 ifstream 从文件读取内容。可以逐行读取或按单词读取。
std::ifstream file("example.txt");std::string line;
if (file.is_open()) {
while (getline(file, line)) {
std::cout }
file.close();
} else {
std::cout }
注意:getline(file, line) 每次读取一行,直到遇到换行符为止。
Perl 基础入门中文教程,chm格式,讲述PERL概述、简单变量、操作符、列表和数组变量、文件读写、模式匹配、控制结构、子程序、关联数组/哈希表、格式化输出、文件系统、引用、面向对象、包和模块等知识点。适合初学者阅读和了解Perl脚本语言。
4. 同时读写文件(fstream)
当你需要对同一个文件进行读写操作时,使用 fstream 类,并指定模式。
std::fstream file("example.txt", std::ios::in | std::ios::out);// 先读取所有内容
std::string content;
while (getline(file, content)) {
std::cout }
// 移动指针到末尾再写入
file
常见打开模式:
- std::ios::in:读取
- std::ios::out:写入(默认会清空文件)
- std::ios::app:追加
- std::ios::ate:打开后立即定位到文件末尾
- std::ios::binary:二进制模式
5. 检查文件是否存在
可以通过尝试打开文件来判断是否存在:
std::ifstream file("example.txt");if (!file) {
std::cout } else {
std::cout file.close();
}
6. 二进制文件读写
对于非文本文件(如图片、音频),应使用二进制模式。
// 写入二进制std::ofstream out("data.bin", std::ios::binary);
int data = 12345;
out.write(reinterpret_cast
out.close();
// 读取二进制
std::ifstream in("data.bin", std::ios::binary);
int value;
in.read(reinterpret_cast
in.close();
std::cout
使用 read() 和 write() 函数处理原始字节数据。
7. 完整示例:读写学生信息
#include#include
#include
int main() {
// 写入数据
std::ofstream out("students.txt");
if (out.is_open()) {
out out out.close();
}
// 读取数据
std::ifstream in("students.txt");
std::string name;
int age;
if (in.is_open()) {
while (in >> name >> age) {
std::cout }
in.close();
}
return 0;
}
基本上就这些。掌握这些方法后,就能处理大多数C++文件操作任务了。关键是记得检查文件是否成功打开,并根据需求选择合适的模式。不复杂但容易忽略细节。










