C++ fstream文件打开问题:如何实现不存在创建、存在覆盖?
问题解决:实现文件不存在创建、存在则覆盖的TextFile类
要满足文件不存在则创建,已存在则覆盖内容的需求,同时保留std::fstream的读写能力,需要调整文件打开的逻辑,具体做法如下:
核心思路
std::fstream的std::ios::in | std::ios::out模式不会自动创建文件,而单独的std::ios::out模式会创建文件并清空原有内容。我们可以结合这两种模式:
- 先尝试用
in | out打开文件,失败则用out模式创建并清空文件,再重新以in | out打开; - 若文件已存在且打开成功,手动将文件指针移到开头并截断文件,确保写入时覆盖全部内容。
修改后的TextFile类代码
#include <fstream> #include "String.h" #include <iostream> class TextFile { std::fstream stream; public: TextFile(const String& filename) { // 第一步:尝试以读写模式打开 stream.open(filename.data(), std::ios::in | std::ios::out); // 如果打开失败(文件不存在) if (!stream.is_open()) { // 先以写模式创建并清空文件 std::ofstream temp(filename.data(), std::ios::out); temp.close(); // 再次以读写模式打开 stream.open(filename.data(), std::ios::in | std::ios::out); } else { // 文件已存在,将指针移到开头并截断内容 stream.seekp(0); stream.trunc(); } std::cout << "File opened " << filename.data() << " " << stream.is_open() << std::endl; } ~TextFile() { close(); } template <typename T> TextFile& operator<<(const T& data) { stream << data; return *this; } TextFile& operator<<(const String& s) { stream << s.data(); return *this; } template <typename T> TextFile& operator>>(T& data) { stream >> data; return *this; } void close() { if (stream.is_open()) stream.close(); } };
代码说明
- 文件创建逻辑:当
fstream打开失败时,用ofstream以std::ios::out模式创建文件,这个模式会自动创建不存在的文件; - 覆盖已有内容:文件存在且打开成功后,调用
seekp(0)将写入指针移到文件开头,再调用trunc()截断文件,后续写入就会完全覆盖原有内容; - 保留读写能力:最终始终以
std::ios::in | std::ios::out模式打开文件,确保后续既可以读也可以写。
内容的提问来源于stack exchange,提问作者Marcell
相关产品推荐
相关产品推荐

