MFC儲存文字檔的兩種方法(包含如何擷取工作路徑)

來源:互聯網
上載者:User

第一種方法,從網上找到的,直接使用了CFile類,其中用的那些古怪的處理其實是為了儲存中文,所以需要添加unicode格式轉化。使用比較抽象而且需要添加標頭檔

#include   <atlconv.h>

CString   str   =   "測試儲存檔案//n";
CString str2 = "附加";
//A2W      (LPCSTR) -> (LPWSTR)
USES_CONVERSION;
unsigned   short*   pstr   =   A2W((LPCTSTR)   str);
int   Len   =   2   *   wcslen(pstr);    
unsigned   short*   pstr2   =   A2W((LPCTSTR)   str2);
int   Len2   =   2   *   wcslen(pstr2);    
CFile   file;
file.Open( "D://123.txt ",   CFile::modeCreate   |   CFile::modeReadWrite   |   CFile::shareDenyWrite,   NULL);
BYTE   UH[]   =   {0xff,   0xfe};
file.Write(UH,   2);
file.Write(pstr,   Len);
file.Write(pstr2,   Len2);
file.Close();

 

第二種方法,一下截自我寫的一段程式,可以直接使用~~

    TCHAR sgCurPath[MAX_PATH];
    ZeroMemory(sgCurPath, sizeof(sgCurPath));
    GetModuleFileName(NULL,sgCurPath,sizeof(sgCurPath)/sizeof(TCHAR));
    CString sgModulePath = sgCurPath;
    sgModulePath = sgModulePath.Left(sgModulePath.ReverseFind('//'));
    sgModulePath = sgModulePath + "//myfile.txt";
    char* saveFileName= (LPSTR)(LPCTSTR)sgModulePath;
// 擷取 當前程式工作目錄~~~~~

    CStdioFile myFile;
    CFileException fileException;
    CString temp_save;

    CTime time = CTime::GetCurrentTime();///構造CTime對象
    int m_nYear = time.GetYear();///年
    int m_nMonth = time.GetMonth();///月
    int m_nDay = time.GetDay();///日
    int m_nHour = time.GetHour();///小時
    int m_nMinute = time.GetMinute();///分鐘
    int m_nSecond = time.GetSecond();///秒
    //擷取當前儲存時間 寫入檔案
    CString m_strTime = time.Format("%Y-%m-%d %H:%M:%S");

    if(myFile.Open(saveFileName,CFile::typeText|CFile::modeCreate|CFile::modeReadWrite| CFile::shareDenyWrite),&fileException)
    {
        //開始向文字檔中寫入myfile,

        m_strTime = "當前儲存時間: "+ m_strTime + "/n";
        myFile.WriteString(m_strTime);
        temp_save = " 這是一個測試程式";

        myFile.WriteString(temp_save);
    }
    else
    {
        TRACE("Can't open file %s,error=%u/n",saveFileName,fileException.m_cause);
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.