第一種方法,從網上找到的,直接使用了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);
}