介紹如何使用 CStdioFile 類去寫檔案。
示例:
1 /// My Add
2 // 擷取目前路徑名
3 WCHAR szPaht[MAX_PATH] = { 0 };
4 GetModuleFileName(NULL, szPaht, sizeof(szPaht));
5 PathRemoveFileSpec(szPaht);
6
7 // 設定你的檔案名
8 CString strFileName("Demo.txt");
9
10 // 将檔案名附加在 目前路徑 裡面
11 wcscat_s(szPaht, L"\\"); ///知道為啥是L 開頭嗎,因為vs2013工程預設是unicode環境,unicode字元串需要 L 開頭的宏
12 wcscat_s(szPaht, strFileName.GetString());
13
14 /// 必須 設定 一下 語言環境,否則 my_log_file.WriteString 不能輸出中文(是不是感覺好複雜?)沒關系,目前工程能跑起來,能夠就行。
15 setlocale(LC_ALL, "chs");
16
17 // 檔案讀寫 StdioFile
18 // 1.建立 CStdioFile的對象,并指定 讀寫檔案的方式。 CFile::modeNoTruncate,不會覆寫之前的檔案。
19 CStdioFile my_log_file(szPaht, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate);
20 /// 這裡将2行代碼合并為1行了。如果分開寫,是這樣的:
21 /// CStdioFile my_log_file;
22 /// my_log_file.Open(szPaht, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate);
23 ////
24
25 // 2.将讀寫指針移到檔案末尾
26 my_log_file.SeekToEnd();
27 // 3.寫入一個字元串
28 CString strData;
29 strData.Format(L"%s", L"早上好,");
30 strData = strData + L"。\r\n";
31 my_log_file.WriteString(strData);
32 // 4.關閉 讀寫指針
33 my_log_file.Close();
因為是在vs2013下建立的工程,預設是unicode編碼,是以就用到了 WCHAR 這樣的字元類型。
這裡面也有 再次介紹 如何 擷取字元串。
這些都不是重點。重點看看 CStdioFile 這個類如何使用。
1.建立這個類的對象;
2.調用open() 方法,打開某個檔案;/ 第1步和第2步可以合并。見代碼第19行。
3.如果有必要,就調用 SeekToEnd(),将檔案指針移到檔案末尾
4.調用WriteString() 寫入檔案;
5.寫完之後,關閉檔案。
必須指出的地方:
1. 需要設定 語言環境(setlocale(LC_ALL, "chs"); ),否則 WriteString() 無法将中文寫入到文本檔案中。
2.我講解的不太清楚,如果你也看得迷迷糊糊的,沒關系,有源碼。可以直接拿來用的。前言部分 有源碼連結。
參考連結:
http://blog.csdn.net/ljz888666555/article/details/5511247
http://blog.csdn.net/jearmy/article/details/39559895