C++ 中文件操作的基础包括文件的读写,文件流的使用,以及如何处理文件操作中可能遇到的问题。我们可以通过 fstream、ifstream、ofstream 这些标准库类来实现文件的操作。
1. 文件操作的基础知识
文件流类型
ofstream(output file stream): 用于向文件写入数据。ifstream(input file stream): 用于从文件读取数据。fstream(file stream): 同时支持读和写操作。
常用文件模式
ios::in: 打开文件用于读取(默认模式为ifstream)。ios::out: 打开文件用于写入(默认模式为ofstream)。ios::app: 以追加模式写入文件,保留文件原内容。ios::trunc: 清空文件内容(默认写入模式,如果文件已存在,会清空原有内容)。ios::binary: 以二进制模式打开文件(默认是文本模式)。
2. 写入文本文件
我们首先使用 ofstream 类来向文件中写入文本。
示例代码:
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 打开文件,注意ios::out是写入模式
std::ofstream outfile("example.txt", std::ios::out);
// 检查文件是否成功打开
if (!outfile) {
std::cerr << "文件无法打开!" << std::endl;
return 1;
}
// 向文件中写入文本
outfile << "这是一行文本。" << std::endl;
outfile << "这是第二行文本。" << std::endl;
// 关闭文件
outfile.close();
std::cout << "写入文件成功!" << std::endl;
return 0;
}
注意事项:
- 每次使用
ofstream打开文件时,如果没有指定ios::app,文件内容会被清空。 - 在写入文件后,务必记得使用
close()关闭文件,否则可能会导致数据未能正确写入。
3. 读取文本文件
我们使用 ifstream 类来从文件中读取数据。
示例代码:
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 打开文件,注意ios::in是读取模式
std::ifstream infile("example.txt", std::ios::in);
// 检查文件是否成功打开
if (!infile) {
std::cerr << "文件无法打开!" << std::endl;
return 1;
}
std::string line;
// 使用getline读取文件每一行
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
// 关闭文件
infile.close();
return 0;
}
注意事项:
- 使用
std::getline()逐行读取文件。 - 检查文件是否成功打开是很重要的,避免操作不存在的文件或路径错误。
4. 文件的随机读写
如果需要在文件的任意位置进行读写,可以使用 seekg() 和 seekp() 来调整文件指针的位置:
seekg(pos):设置文件的读取位置。seekp(pos):设置文件的写入位置。
示例代码:
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 以读写模式打开文件
std::fstream file("example.txt", std::ios::in | std::ios::out);
if (!file) {
std::cerr << "文件无法打开!" << std::endl;
return 1;
}
// 移动写入位置到文件开始的第10个字符
file.seekp(10);
file << "插入内容";
// 移动读取位置到文件开始
file.seekg(0);
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
return 0;
}
5. 常见坑和注意事项
-
忘记检查文件是否成功打开: 文件操作前一定要检查文件是否成功打开,否则可能会出现未预料的行为。
-
文件路径问题: 文件路径应当正确,最好使用绝对路径或者检查当前的工作目录。
-
文件权限问题: 确保具有对文件的读写权限,尤其是在多用户环境下。
-
二进制与文本模式的区别: 如果是处理非文本文件(如图像、音频等),应使用二进制模式打开文件 (
ios::binary),否则可能出现数据损坏。 -
文件操作失败后不处理: 如果文件操作失败(例如磁盘已满),未能及时检测并处理错误,可能会导致数据丢失。
6. 完整的示例
以下是一个将文本写入文件并读取文件的完整示例:
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 写入文件
std::ofstream outfile("example.txt", std::ios::out);
if (!outfile) {
std::cerr << "无法打开文件进行写入" << std::endl;
return 1;
}
outfile << "C++ 文件操作示例" << std::endl;
outfile << "这是文件操作的测试。" << std::endl;
outfile.close();
// 读取文件
std::ifstream infile("example.txt", std::ios::in);
if (!infile) {
std::cerr << "无法打开文件进行读取" << std::endl;
return 1;
}
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
infile.close();
return 0;
}
1890

被折叠的 条评论
为什么被折叠?



