答案:C++中使用fstream头文件提供的ofstream、ifstream和fstream类进行文件读写操作,其中ofstream用于写入文件,ifstream用于读取文件,fstream支持同时读写;通过构造对象并传入文件名打开文件,使用.is_open()判断是否成功,写入时可选择默认覆盖或ios::app追加模式,读取时常用getline按行获取内容,操作完成后需调用.close()关闭文件。

在C++中进行文件读写操作,主要使用标准库中的 fstream 头文件,它提供了三个核心类:
下面详细介绍如何使用这些类进行常见的文件读写操作。
使用 ofstream 可以轻松创建或覆盖一个文件,并将数据写入其中。
立即学习“C++免费学习笔记(深入)”;
#include <fstream>
#include <iostream>
using namespace std;
<p>int main() {
ofstream outFile("example.txt");</p><pre class='brush:php;toolbar:false;'>if (outFile.is_open()) {
outFile << "Hello, this is a test.\n";
outFile << "Second line of text.\n";
outFile.close();
cout << "文件写入成功!\n";
} else {
cout << "无法打开文件!\n";
}
return 0;}
说明:
使用 ifstream 读取已有文件的内容。
立即学习“C++免费学习笔记(深入)”;
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
<p>int main() {
ifstream inFile("example.txt");
string line;</p><pre class='brush:php;toolbar:false;'>if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "无法打开文件!\n";
}
return 0;}
说明:
如果不想覆盖原文件内容,可以使用追加模式(app)。
立即学习“C++免费学习笔记(深入)”;
ofstream outFile("example.txt", ios::app);
if (outFile.is_open()) {
outFile << "This line is appended.\n";
outFile.close();
}
常用文件模式标志:
当需要对同一个文件进行读写操作时,使用 fstream 类。
立即学习“C++免费学习笔记(深入)”;
fstream file("data.txt", ios::in | ios::out | ios::app);
if (file.is_open()) {
file << "Appending new data.\n";
file.seekg(0); // 移动读指针到开头
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
注意: 使用 fstream 时,要合理控制读写指针位置。常用函数:
基本上就这些。掌握 ifstream、ofstream 和 fstream 的基本用法后,就能处理大多数文本文件操作需求。对于二进制文件,只需添加 ios::binary 标志,并使用 .read() / .write() 方法。操作完成后记得关闭文件,避免资源泄漏。
以上就是c++++如何读取和写入文件_c++文件读写操作方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号