答案:C++通过fstream库实现文件读写,ofstream写入、ifstream读取、fstream支持读写;写入时默认覆盖内容,可设追加模式,需检查文件是否成功打开。

在C++中读写txt文件是常见的操作,主要通过标准库中的 fstream 头文件来实现。这个头文件提供了三个关键类:
要将数据写入文本文件,可以使用 ofstream。默认情况下,写入会覆盖原内容,也可以设置为追加模式。
#include <iostream>
#include <fstream>
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 可以从文本文件中读取内容。有多种方式读取:按行、按词或整个文件。
Android文件存取与数据库编程知识,文件操作主要是读文件、写文件、读取静态文件等,同时还介绍了创建添加文件内容并保存,打开文件并显示内容;数据库编程方面主要介绍了SQLite数据库的使用、包括创建、删除、打开数据库、非查询SQL操作指令、查询SQL指令-游标Cursors等知识。
17
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <fstream>
#include <string>
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 <iostream>
#include <fstream>
#include <string>
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;
}
以上就是c++++ 读写txt文件 c++文件读写操作教程的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号