ofstream 创建文件但未在 C++ 中写入文件

Sam*_*erg 5 c++ mfc ofstream

我正在编写一个 MFC 程序,该程序有一个带有“导出”按钮的对话框,该按钮将获取已输入文件中的所有数据并将其导出到 .txt(有时我想将其更改为 .msg)文件...但这是另一天的问题)。

但是,当我单击该按钮时,它会创建文件,但不会在文件中写入任何内容。为了进行测试,我删除了除简单文字字符串之外的所有内容,甚至不打印。以下是该事件的当前代码: myfile.flush() 语句是我尝试打印到文件的循环时剩下的。

void CEHDAHTTimerDlg::OnBnClickedExport()
{
    // in this function, we want to export the items to a text file
    std::ofstream myfile("TodayTime.txt");
    myfile.open("TodayTime.txt");
    if (myfile.is_open())
    {
        myfile << "The average call time is ";
        myfile.flush();
        myfile.close();
    }
    else
    {
        SetDlgItemText(IDC_EXPORT, L"Export Unsuccessful! --     No File");
    }
}
Run Code Online (Sandbox Code Playgroud)

大家能想到有什么可能导致这种情况吗?我已经花了几个小时尝试不同的事情,比如使用 myfile.write() 函数。我在这里、reddit 和谷歌上搜索了很多,试图找出为什么这没有写出来。

我感谢您的帮助。

编辑:

好的,按照我的方式调用 myfile 构造函数,通过包含文件名,继续执行打开文件会执行的操作

感谢您的帮助!

Ric*_*ges 6

注释掉多余的“open”就可以解决这个问题。

#include <iostream>
#include <fstream>

int main()
{
    // in this function, we want to export the items to a text file
    std::ofstream myfile("TodayTime.txt");
//    myfile.open("TodayTime.txt");
    if (myfile.is_open())
    {
        myfile << "The average call time is ";
        myfile.flush();
        myfile.close();
    }
    else
    {
        std::cerr << "didn't write" << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

我强烈怀疑您通过打开和已经打开的流来调用未定义的行为。