C++通过fstream头文件实现txt文件读写,使用ofstream写入、ifstream读取、fstream支持同时读写。首先包含<fstream>等头文件,写文件时创建ofstream对象并检查是否打开,用<<写入内容,追加需ios::app;读文件用ifstream和getline逐行读取或>>按词读取;fstream结合ios::in和ios::out实现读写,操作后需close()。

C++ 读取和写入 txt 文件主要使用 fstream 头文件中的类:ifstream(读文件)、ofstream(写文件)和 fstream(可读可写)。操作简单,适合处理文本数据。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
示例代码:
ofstream outFile("data.txt");
if (outFile.is_open()) {
outFile << "第一行内容" << endl;
outFile << "第二行内容" << endl;
outFile.close();
} else {
cout << "无法打开文件写入!" << endl;
}
ofstream outFile("data.txt", ios::app);
示例:逐行读取
立即学习“C++免费学习笔记(深入)”;
ifstream inFile("data.txt");
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "无法打开文件读取!" << endl;
}
string word;
while (inFile >> word) {
cout << word << endl;
}
fstream file("data.txt", ios::in | ios::out);
// 先读再写,或根据需要定位
基本上就这些。打开文件记得判断是否成功,操作完要 close()。对于简单的配置或日志记录,txt 文件读写非常实用。
以上就是c++++怎么读取和写入txt文件_c++ txt文件读写方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号