操作文本文件簡介

        今天在使用std::fstream操作文件時,與到一個問題seek(std::ios::end)與seekg(0, std::ios::end)的差異。雖然查閱各種資料,然而還是無解,希望有深入理解C++標準高手指點一二。

        閒話少說,先看如下代碼

void CExceptionManager::ExceptionRecord(const std::string& text)
	{
		//構造異常記錄文件名, 文件路徑
		CTime t = CTime::GetCurrentTime();
		std::string filename, filepath;		
		std::stringstream ss;
		ss << t.GetYear() << t.GetMonth() << t.GetDay() << ".txt";
		ss >> filename;
		filepath = ".\\Log\\CCTS\\Exception\\" + filename;
		
		//創建文件流
		//std::fstream 繼承了 std::ifstream & std::ofstream, 二者的操作都是以內存爲基準, 操作都是相對於內存來說的
		//std::ifstream : 將文本文件數據輸入內存
		//std::ofstream : 將內存的數據輸出至文本文件
		std::fstream fs(filepath.c_str(), std::ios::app | std::ios::in);
		if (fs.fail())
          {
            throw std::exception("呃...什麼鬼? 文本操作竟然都出現異常?");
          }
		//判斷文件內容是否爲空?: 先將標記定位至輸入流的 std::ios::end 位置, 然後讀取標記讀取的位置; 如果標記爲0, 則內容爲空
        //注意: 一定要將 offset 設置爲 0, 否則會有問題, 雖然 MSDN 並不支持這樣做 
		fs.seekg(0, std::ios::end);
		//然後獲取標記讀取位置
		std::streamoff pos = fs.tellg();
		if (0 == pos)
		{//如果位置等於0, 則可以說明文件內的數據爲空, 這時要寫入一串"*"
			std::string s(128, '*');
			fs << s << "\r\n";
		}
		fs << text;
		fs.close();
	}

以上代碼看似沒有問題,然而如果將 "fs.seekg(0, std::ios::end);" 改爲 "fs.seekg(std::ios::end);"; 那麼將會出現如下問題:
1. "tellg()" 返回值永遠是 2 ?

2. MSDN裏面有段原話: Do not use the second member function with text files, because Standard C++ does not support relative seeks in text files. 也就是說,在文本文件裏C++不支持使用相對搜索,然而,這裏卻使用的好好的,相反使用fs.seekg(std::ios::end);出現了問題。這又是爲何?

求好心的大神解釋。


發佈了26 篇原創文章 · 獲贊 19 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章