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

Visual Studio(C++/Win11)中ifstream正常但ofstream文件不可见

问题:C++ ofstream显示文件已打开但找不到output.txt

我编写了一个包含ifstream和ofstream的简单C++程序,ifstream可正常读取input.txt,但ofstream虽显示已打开,却无法在目录中找到生成的output.txt。我尝试关闭COMODO杀毒软件,问题仍存在。请问是什么原因导致无法看到输出文件?

我的First.cpp代码

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream output("output.txt");
    ifstream input("input.txt");
    if (output.is_open()) {
        cout << "ouput file is open" << endl;
        output << "hi";
    }
    else {
        cout << "output file is not open" << endl;
    }
    int number;
    if (input.is_open()) {
        cout << "input file is open" << endl;
        input >> number;
        cout << "Number:" << number << endl;
    }
    else {
        cout << "input file is not open" << endl;
    }
    input.close();
    output.close();
    return 0;
}

input.txt内容

21
12
22
23
32

程序运行输出

ouput file is open
input file is open
Number:21

可能的原因及解决方法

  • 输出文件不在预期目录:程序的工作目录未必是你存放源码的目录。比如用IDE编译时,默认工作目录可能是项目的Debug/Release子文件夹,或者编译后可执行文件所在的路径。可以尝试使用绝对路径指定输出文件(例如ofstream output("C:/Users/xxx/Documents/output.txt");),也可以在程序中添加代码打印当前工作目录:
    // Windows下
    char buf[256];
    _getcwd(buf, sizeof(buf));
    cout << "当前工作目录:" << buf << endl;
    
  • 文件被隐藏:检查文件夹的显示设置,开启「显示隐藏的文件、文件夹和驱动器」,查看是否output.txt被标记为隐藏文件。
  • 权限不足:如果程序运行的目录是系统保护目录(如C:\Program Files),当前用户可能没有写入权限。尝试右键以管理员身份运行程序,或者将项目移到普通用户目录(如文档、桌面)。
  • 缓冲区未正常刷新(概率较低):虽然调用close()会自动刷新缓冲区,但极端情况下可能出现异常。可以在写入内容后手动调用output.flush();确保内容写入磁盘。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:45:29