C++的文件操作允许我们读取和写入文件,这对于保存数据、读取配置文件或进行持久化存储非常有用。文件操作主要涉及到std::ifstream(输入文件流)和std::ofstream(输出文件流),它们分别用于从文件中读取数据和向文件中写入数据。让我们详细讲解C++的文件操作:
文件写入(输出流):
使用std::ofstream来创建一个输出文件流,并使用<<运算符将数据写入文件。
#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("example.txt"); // 创建输出文件流
if (outFile.is_open()) {
outFile << "This is a line of text." << std::endl;
outFile << "This is another line of text." << std::endl;
outFile.close();
std::cout << "File write successful!" << std::endl;
} else {