摘要:
使用c++讀寫二進位制檔案,在開發中操作的比較頻繁,今天有幸找到一篇文章,遂進行了一些試驗,並進行了部分的總結。
使用c++操作檔案,是研發過程中比較頻繁的,因此進行必要的總結和封裝還是十分有用的。今天在網上找到一篇,遂進行了部分的試驗,以記之,備後用。
本文讀寫檔案均使用檔案流進行操作,主要使用的類是
ifstream, ofstream,
使用時,請務必包含檔案fstream。如下:
#include
寫二進位制檔案
寫二進位制檔案應該使用ofstream類,檔案的開啟模式一定要是 binary,如果傳入的不是 binary, 檔案將以ascii方式開啟。
下面是示例**,用於寫入檔案。
std::ofstream fout("a.dat", std::ios::binary);
int nnum = 20;
std::string str("hello, world");
fout.write((char*)&nnum, sizeof(int));
fout.write(str.c_str(), sizeof(char) * (str.size()));
fout.close();
而寫文字檔案則比較簡單,如下:
std::ofstream fout("b.dat");
int nnum = 20;
std::string str("hello, world");
fout << nnum << "," << str << std::endl;
fout.close();
讀二進位制檔案
讀取二進位制檔案可以使用ifstream 類來進行,檔案的開啟模式一定要是 binary,如果傳入的不是 binary, 檔案將以ascii方式開啟。
下面是示例**:
std::ifstream fin("a.dat", std::ios::binary);
int nnum;
char szbuf[256] = ;
fin.read((char*)&nnum, sizeof(int));
fin.read(szbuf, sizeof(char) * 256);
std::cout << "int = " << nnum << std::endl;
std::cout << "str = " << szbuf << std::endl;
fin.close();
而讀取文字檔案則比較簡單:
std::ifstream fin("b.dat");
int nnum;
char szbuf[256] = ;
fin >> nnum >> szbuf;
std::cout << "int = " << nnum << std::endl;
std::cout << "str = " << szbuf << std::endl;
fin.close();
檔案的開啟模式
檔案操作時,如果不顯示指定開啟模式,檔案流類將使用預設值。
在中定義了如下開啟模式和檔案屬性:
ios::ate // 開啟並找到檔案尾
ios::binary // 二進位制模式i/o(與文字模式相對)
ios::in // 唯讀開啟
ios::out // 寫開啟
ios::trunc // 將檔案截為 0 長度
可以使用位操作符 or 組合這些標誌,比如
二進位制檔案的複製
這裡我實現了乙個二進位制檔案的複製操作,用於驗證讀寫的正確性,示例**如下:
[cpp]view plain
copy
bool
copy_binary_file(
const
char
* szdestfile,
const
char
* szorigfile)
if(szorigfile == null)
bool
bret =
true
; std::ifstream fin(szorigfile, std::ios::binary);
if(fin.bad())
else
; fin.read(szbuf, sizeof
(char
) * 256);
if(fout.bad())
// fout.write(szbuf, sizeof
(char
) * 256);
} }
fin.close();
fout.close();
return
bret;
}
後記
由於文字檔案本質上也是磁碟上的乙個個二進位制編碼,因此,讀寫二進位制檔案的**同樣可以讀寫文字檔案,在檔案型別不是很明確的讀寫操作中,直接使用二進位制讀寫比較可取,如果可以直接判斷檔案型別,則可以分別對待。
關於讀取文字檔案,請參照
C 讀寫二進位制檔案
摘要 使用c 讀寫二進位制檔案,在開發中操作的比較頻繁,今天有幸找到一篇文章,遂進行了一些試驗,並進行了部分的總結。使用c 操作檔案,是研發過程中比較頻繁的,因此進行必要的總結和封裝還是十分有用的。今天在網上找到一篇,遂進行了部分的試驗,以記之,備後用。include 寫二進位制檔案 寫二進位制檔案...
c 讀寫二進位制檔案
最近需要用到二進位制檔案讀寫的相關操作,這邊稍微總結下,首先二進位制檔案的讀寫可以使用fread和fwrite來處理。fread函式原型 size t cdecl fread void size t,size t,file 第乙個引數表示的是快取,第二個引數表示的是基本單元的大小,第三引數表示的是基...
C 二進位制檔案讀寫
今天終於弄明白怎樣使用c 讀寫二進位制檔案了。要讀取檔案必須包含標頭檔案,這裡包含了c 讀寫檔案的方法。可以使用fstream類,這個類可以對檔案進行讀寫操作。1 開啟檔案。可以寫檔案了,讀檔案就好辦多了。讀檔案需要用到read函式。其引數和write大致相同,read const char ch,...