Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

ofstream

mfc

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!

like image 635
Samuel Ohrenberg Avatar asked Feb 08 '23 02:02

Samuel Ohrenberg


2 Answers

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.

like image 156
Richard Hodges Avatar answered Feb 09 '23 16:02

Richard Hodges


Here is the explanation:

  1. The call to myfile.open("TodayTime.txt"); will fail because the stream is already associated with the file, setting the failbit.
  2. The call to is_open() will succeed, as the file is open.
  3. Then the call to streaming operator << will fail (because of the failbit).
like image 45
Vlad Feinstein Avatar answered Feb 09 '23 16:02

Vlad Feinstein