完整範例程式碼
char *pFileName = "test.txt";
CStdioFile sf;
if (!sf.Open(pFileName, CFile::modeCreate | CFile::modeReadWrite | CFile::typeText)) {
#ifdef _DEBUG
afxDump << "Unable to open file" << "\n";
#endif
exit(1);
}
char aaa[] = "aaa\n"; // '\n' = 0x0A
char *bbb = "bbb\12"; // '\12' = 0x0A
CString ccc("ccc\15"); // '\15' = 0x0D
sf.WriteString(aaa);
sf.WriteString(bbb);
sf.WriteString(ccc);
sf.WriteString("ddd\r"); // '\r' = 0x0D
sf.Close();
// 讀取測試
CStdioFile sf2("test.txt", CFile::modeRead | CFile::typeText);
char buf[8];
CString str;
LPTSTR lpstr = sf2.ReadString(buf, 8);
AfxMessageBox(buf);
while (sf2.ReadString(str))
AfxMessageBox(str);
sf2.Close();
說明
CFile::typeText 會自動處理換行符轉換(\n ↔ \r\n)。
WriteString 寫入字串,ReadString 可讀入緩衝區或 CString。
- 範例展示不同換行寫法(\n、\12、\15、\r)在文字模式下的實際儲存行為。