VS2008, MFC 文件的操作1 - C語言方式 文本方式打開 / 二進制方式打開 讀寫 C

1. 在菜單欄 新建 子菜單File 和菜單項 WriteFile,ReadFlile,並都添加 事件處理函數到工程view類中。

2. 以文本新式打開 讀寫文件代碼

void Cvs2008_SX_jiaocheng12View::OnFileWritefile()
{
	// TODO: 在此添加命令處理程序代碼
	//C語言方式
	FILE *pFile = fopen("1.txt","w");//Opens an empty file for writing. If the given file exists, its contents are destroyed.
	fwrite("The last journey to MFC ",1,strlen("The last journey to MFC "),pFile);//文件寫入字符串。
	fwrite("The last journey to MFC ",1,strlen("The last journey to MFC "),pFile);//文件寫入字符串。
	fwrite("The last journey to MFC ",1,strlen("The last journey to MFC "),pFile);//文件寫入字符串。//fwrite 會自動移動文件指針到結尾。

	fseek(pFile,0,SEEK_SET);//SEEK_SET 把文件指針移動頭開始處,可以使用fseek函數來控制文件指針的位置。
	fwrite("xxxxxxxxxx ",1,strlen("xxxxxxxxxx "),pFile);//文件寫入字符串。
	fflush(pFile);//該函數是讓緩存數據寫入文件。
	fclose(pFile);//寫完記得關閉文件

}

void Cvs2008_SX_jiaocheng12View::OnFileReadfile()
{
	// TODO: 在此添加命令處理程序代碼
	//C語言方式
	FILE *pFile = fopen("1.txt","r");//Opens for reading. If the file does not exist or cannot be found, the fopen call fails.

    if(NULL == pFile)
	{
		MessageBox(_T("Open file error "));
		return ;//退出 防止繼續非法訪問
	}

    /*方式1
	char ch[100];
//	memset(ch,0,100);//寫0以保持 輸出有\0,這樣輸出就有結尾了。這是一種方式
	fread(ch,1,100,pFile);//以1字節形式 最大讀取100個字節到ch中
    //char 和wchar 轉換
	int num = MultiByteToWideChar(0,0,ch,-1,NULL,0);
	wchar_t *wide = new wchar_t[num];
	MultiByteToWideChar(0,0,ch,-1,wide,num);

	MessageBox(wide);
	*/
	//方式2
	char *pBuf;
	fseek(pFile,0,SEEK_END);//首先把文件指針移動到末尾
	int len = ftell(pFile);//獲取文件長度
	pBuf = new char[len + 1];//開闢長度
	//fseek(pFile,0,SEEK_SET);//把文件移動到開始處。
	rewind(pFile);//這個函數也是把 文件指針放到開始處。
	fread(pBuf,1,len,pFile);
	pBuf[len] = 0;
	
	//char 和wchar 轉換
	int num = MultiByteToWideChar(0,0,pBuf,-1,NULL,0);
	wchar_t *wide = new wchar_t[num];
	MultiByteToWideChar(0,0,pBuf,-1,wide,num);
	
	MessageBox(wide);
	delete[] pBuf;
	

	fclose(pFile);//寫完記得關閉文件

}

 

3. 以二進制形式打開

以文本 形式寫入的數據 有換行10 (0xA)則會被轉換爲回車(0xD)加換行(0xA),所以會增加一個字符,讀取的時候則反着來 去掉了回車;以二進制 則不會。二進制 文件 一般是可執行文件 聲碼等。(重點強調,以什麼方式寫數據,就以什麼方式去讀!這樣就不會出問題。)

void Cvs2008_SX_jiaocheng12View::OnFileWritefile()
{
	// TODO: 在此添加命令處理程序代碼
	//C語言方式
	FILE *pFile = fopen("2.txt","wb");
	char ch[3];
	ch[0] = 'a';
	ch[1] = 10;//換行
	ch[2] = 'b';
	fwrite(ch,1,3,pFile);
	fclose(pFile);
}

void Cvs2008_SX_jiaocheng12View::OnFileReadfile()
{
	// TODO: 在此添加命令處理程序代碼
	//C語言方式
	FILE *pFile = fopen("2.txt","rb");//Opens for reading. If the file does not exist or cannot be found, the fopen call fails.
	                                  //Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed. 


	char ch[100];
	fread(ch,1,3,pFile);
	ch[3] = 0;
	
	//char 和wchar 轉換
	int num = MultiByteToWideChar(0,0,ch,-1,NULL,0);
	wchar_t *wide = new wchar_t[num];
	MultiByteToWideChar(0,0,ch,-1,wide,num);

	MessageBox(wide);
	fclose(pFile);
}

4. 對二進制文件 和文本文件 都可以用 二進制和文本方式打開訪問的(不要混淆 文件類型與打開方式)。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章