C++通过fstream头文件中的ofstream、ifstream和fstream类实现文件读写,分别用于写入、读取和同时读写文件。操作时需先打开文件,可用构造函数或open()方法,完成后调用close()关闭。例如:std::ofstream outFile("example.txt"); 若文件成功打开,可通过is_open()判断并进行写入操作。

在C++中,读取和写入文件主要通过标准库中的fstream头文件提供的文件流类来实现。这些类包括ifstream(用于读取文件)、ofstream(用于写入文件)和fstream(可同时读写)。下面详细介绍它们的使用方法。
要操作文件,首先要打开它。可以使用构造函数或open()方法打开文件,操作完成后调用close()关闭文件。
示例:使用构造函数打开文件
#include <fstream>
#include <iostream>
int main() {
std::ofstream outFile("example.txt"); // 自动打开文件
if (outFile.is_open()) {
outFile << "Hello, World!" << std::endl;
outFile.close(); // 关闭文件
} else {
std::cout << "无法打开文件进行写入" << std::endl;
}
return 0;
}
ofstream用于将数据写入文件,支持使用<<操作符写入字符串、数字等基本类型。
立即学习“C++免费学习笔记(深入)”;
示例:追加写入文件
std::ofstream outFile("log.txt", std::ios::app);
if (outFile) {
outFile << "新日志条目\n";
}
outFile.close();
ifstream用于从文件读取数据,可以用>>操作符逐个读取单词,或用getline()读取整行。
示例:逐行读取文件
#include <string>
std::ifstream inFile("data.txt");
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
fstream允许对同一文件进行读写操作,需指定打开模式如std::ios::in | std::ios::out。
示例:读写同一个文件
std::fstream file("config.txt", std::ios::in | std::ios::out);
if (file.is_open()) {
std::string content;
std::getline(file, content);
file << "\n更新内容";
file.close();
}
基本上就这些。掌握ifstream、ofstream和fstream的基本用法,就能满足大多数文件操作需求。注意每次操作后检查文件是否成功打开,并及时关闭资源。不复杂但容易忽略细节。
以上就是c++++中如何读取和写入文件_c++文件输入输出流使用方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号