

新闻资讯
技术学院答案:C++通过fstream库实现文件读写,ofstream写入、ifstream读取、fstream支持读写;写入时默认覆盖内容,可设追加模式,需检查文件是否成功打开。
在C++中读写txt文件是常见的操作,主要通过标准库中的 fstream 头文件来实现。这个头文件提供了三个关键类:
要将数据写入文本文件,可以使用 ofstream。默认情况下,写入会覆盖原内容,也可以设置为追加模式。
#include#include using namespace std; int main() { ofstream outFile("example.txt"); if (outFile.is_open()) { outFile << "Hello, this is a line.\n"; outFile << "This is another line.\n"; outFile.close(); cout << "文件写入成功!\n"; } else { cout << "无法打开文件!\n"; } return 0; }
如果想追加内容而不是覆盖,可以这样打开文件:
ofstream outFile("example.txt", ios::app);
使用 ifstream 可以从文本文件中读取内容。有多种方式读取:按行、按词或整个文件。
#include#include #include using namespace std; int main() { ifstream inFile("example.txt"); string line; if (inFile.is_open()) { while (getline(inFile, line)) { cout << line << endl; } inFile.close(); } else { cout << "无法打开文件!\n"; } return 0; }
说明:getline 每次读取一行,适合处理包含空格的文本。
当你需要对同一个文件进行读写操作时,使用 fstream 更合适。
#include#include
#include using namespace std; int main() { fstream file("example.txt", ios::in | ios::out | ios::app); // 先写入 file << "Added via fstream.\n"; // 移动读指针到开头,再读取 file.seekg(0); // 定位到文件开头 string line; while (getline(file, line)) { cout << line << endl; } file.close(); return 0; }