ofstream creating file but not writing to it in C++

Samuel Ohrenberg picture Samuel Ohrenberg · May 4, 2016 · Viewed 9.1k times · Source

I am writing an MFC program that has a dialog with an "Export" button that will take all of the data that has been entered into the file and export it to a .txt (at some point I want to change this to a .msg file...but that's a question for another day).

However, when I click the button, it creates the file but doesn't write anything inside the file. For testing, I removed everything except just a simple literal string and even that isn't printing. Here is the current code for that event: The myfile.flush() statement is leftover from when I had a loop that I was trying to print to the file.

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");
    }
}

Is there anything you all can think of that could be causing this? I've been at it for a few hours trying different things, like utilizing a myfile.write() function instead. I've searched a lot around here, reddit, and google in general trying to find out why this isn't writing.

I appreciate your help.

EDIT:

Okay, calling the myfile constructor the way that I did, by including the file name, went ahead and did what open file would have done

Thanks for your help!

Answer

Richard Hodges picture Richard Hodges · May 4, 2016

commenting out the redundant "open" solves it.

#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;
    }
}

I strongly suspect that you're invoking undefined behaviour by opening and already-open stream.