gpt4 book ai didi

c++ - ofstream 创建文件但不在 C++ 中写入

转载 作者:行者123 更新时间:2023-11-30 02:31:53 29 4
gpt4 key购买 nike

我正在编写一个 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");
}
}

有没有你们能想到的可能导致这种情况的原因?我已经花了几个小时尝试不同的东西,比如改用 myfile.write() 函数。我在这里、reddit 和 google 上搜索了很多,试图找出为什么这不是写的。

感谢您的帮助。

编辑:

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

感谢您的帮助!

最佳答案

注释掉多余的“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;
}
}

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

关于c++ - ofstream 创建文件但不在 C++ 中写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034247/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com