You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C++的ofstream成功保存创建的文件?

解决文件保存失败的问题

核心问题与修复方案

  • 转义字符错误:你代码里的路径"data\authors.txt"存在转义问题——\a是C++的特殊转义字符(代表响铃),实际解析后路径变成了dataauthors.txt,完全偏离预期。修正方式:

    • 使用双反斜杠:"data\\authors.txt"
    • 或者使用正斜杠:"data/authors.txt"(跨平台兼容性更好)
  • 缺失目录创建逻辑:C++的ofstream不会自动创建不存在的目录。如果你的程序运行目录下没有data文件夹,需要手动创建,或者在代码里添加创建目录的逻辑:

    // Windows平台用这个头文件和函数
    #include <direct.h>
    _mkdir("data"); // 目录已存在时会返回错误,可忽略该错误
    

    (如果是Linux/macOS,替换为#include <sys/stat.h>,调用mkdir("data", 0777);)

  • 确认工作目录:程序默认在当前工作目录(不一定是你的代码文件所在目录)创建文件。比如用IDE运行时,工作目录可能是项目根目录而非src文件夹。可以添加代码输出当前目录确认:

    #include <direct.h>
    cout << "当前工作目录:" << _getcwd(nullptr, 0) << endl;
    
  • 添加错误检查:打开文件后判断是否成功,避免默默失败:

    ofstream file("data\\authors.txt");
    if (!file.is_open()) {
        cerr << "无法打开文件!" << endl;
        return 1;
    }
    

修正后的完整代码

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <direct.h> // Windows平台,Linux/macOS替换为<sys/stat.h>

using namespace std;

int main()
{
    string name;
    vector<string> authors {};
    cout << "Add Author Name: ";
    cin >> name;

    authors.push_back(name);
    
    // 创建data目录
    _mkdir("data");

    ofstream file("data\\authors.txt");
    if (!file.is_open()) {
        cerr << "无法打开文件进行写入!" << endl;
        return 1;
    }
    file << name;
    file.close();

    cout << "作者名已成功保存!" << endl;
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:20:32