You need to enable JavaScript to run this app. 使用std::fstream如何实现仅当文件存在时才进行读写操作
优惠活动
大模型
产品
解决方案
定价
更多

使用std::fstream如何实现仅当文件存在时才进行读写操作

问题原因

自动创建文件的行为是std::ios::app标志导致的。C++标准中规定,当打开模式组合中包含std::ios::app、std::ios::out任意一个时,若文件不存在默认会触发创建逻辑。你使用的std::ios::in | std::ios::out | std::ios::app组合中,std::ios::app的优先级高于std::ios::in原本“文件不存在则打开失败”的默认逻辑,因此即便设置了读权限,文件不存在时依然会自动创建空文件。

解决方案

可以根据编译环境选择以下两种实现方式:

方式1:先校验文件存在性再打开(兼容全版本C++)

如果使用C++17及以上版本,直接用<filesystem>标准库判断文件是否存在:

#include <fstream>
#include <filesystem>

if (std::filesystem::exists("myfile.txt")) {
    std::fstream file("myfile.txt", std::ios::in | std::ios::out | std::ios::app);
    // 后续读写逻辑
}

如果使用C++17以下版本,可以先通过只读流尝试打开校验存在性:

#include <fstream>

std::ifstream test_exist("myfile.txt");
if (test_exist.is_open()) {
    test_exist.close();
    std::fstream file("myfile.txt", std::ios::in | std::ios::out | std::ios::app);
    // 后续读写逻辑
}

方式2:使用C++23新增的std::ios::noreplace标志

如果编译器支持C++23标准,可以直接在打开模式中新增std::ios::noreplace标志,明确要求文件不存在时直接打开失败,不会创建新文件:

std::fstream file("myfile.txt", std::ios::in | std::ios::out | std::ios::app | std::ios::noreplace);
if (file.is_open()) {
    // 文件存在,执行读写逻辑
}

内容的提问来源于stack exchange,提问作者carraro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 01:54:03