簡體   English   中英

ofstream 創建文件但不在 C++ 中寫入

[英]ofstream creating file but not writing to it in C++

我正在編寫一個 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 構造函數,通過包含文件名,繼續執行打開文件會做的事情

感謝您的幫助!

注釋掉多余的“開放”可以解決它。

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

我強烈懷疑您通過打開和已經打開的流來調用未定義的行為。

這是解釋:

  1. 調用myfile.open("TodayTime.txt"); 將失敗,因為流已經與文件關聯,設置了失敗位。
  2. is_open()的調用將成功,因為文件已打開。
  3. 然后對流操作符<<的調用將失敗(由於故障位)。

這是因為myfile << "The average call time is "; 無法解決這個問題

std::ofstream myfile;
myfile.open("TodayTime.txt",std::ios:app) //app for appending you can use trunc for
  //truncating file 
  //for flushing content's of existing file use myfile.flush();
if (!data_pack.is_open())
{
    std::cerr << "unable to open the file for writing";
}

 myfile << "some stuff tho write you can replace the string with variable"
  <<std::endl; //for next line
  //at last close file
   myfile.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM