您的位置:首页 > 其它

MFC保存文本文件的两种方法(包含如何获取工作路径)

2010-07-21 10:55 751 查看
第一种方法,从网上找到的,直接使用了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);
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: