使用fstream配合ios::binary模式進(jìn)行二進(jìn)制文件讀寫,通過write()和read()函數(shù)以字節(jié)形式存取數(shù)據(jù),適用于數(shù)組、結(jié)構(gòu)體等類型,需注意指針和STL容器需手動(dòng)序列化。
在C++中讀寫二進(jìn)制文件,主要使用標(biāo)準(zhǔn)庫(kù)中的 fstream 類,通過設(shè)置適當(dāng)?shù)拇蜷_模式來實(shí)現(xiàn)二進(jìn)制I/O操作。與文本文件不同,二進(jìn)制文件以原始字節(jié)形式存儲(chǔ)數(shù)據(jù),不會(huì)進(jìn)行字符轉(zhuǎn)換,適合保存結(jié)構(gòu)體、類對(duì)象或數(shù)值數(shù)組等。
示例:將一個(gè)整數(shù)數(shù)組寫入二進(jìn)制文件
#include <fstream> #include <iostream> int main() { std::ofstream file("data.bin", std::ios::out | std::ios::binary); if (!file) { std::cerr << "無法打開文件!" << std::endl; return 1; } int arr[] = {10, 20, 30, 40, 50}; int size = sizeof(arr) / sizeof(arr[0]); file.write(reinterpret_cast<const char*>(arr), sizeof(arr)); file.close(); std::cout << "數(shù)據(jù)已寫入 data.bin" << std::endl; return 0; }
示例:從二進(jìn)制文件讀取整數(shù)數(shù)組
巧文書是一款A(yù)I寫標(biāo)書、AI寫方案的產(chǎn)品。通過自研的先進(jìn)AI大模型,精準(zhǔn)解析招標(biāo)文件,智能生成投標(biāo)內(nèi)容。
#include <fstream> #include <iostream> int main() { std::ifstream file("data.bin", std::ios::in | std::ios::binary); if (!file) { std::cerr << "無法打開文件!" << std::endl; return 1; } int arr[5]; file.read(reinterpret_cast<char*>(arr), sizeof(arr)); if (file.gcount() != sizeof(arr)) { std::cerr << "讀取數(shù)據(jù)不完整!" << std::endl; } else { std::cout << "讀取的數(shù)據(jù):"; for (int i = 0; i < 5; ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; } file.close(); return 0; }
示例:保存和讀取學(xué)生信息結(jié)構(gòu)體
立即學(xué)習(xí)“C++免費(fèi)學(xué)習(xí)筆記(深入)”;
#include <fstream> #include <iostream> #include <string> struct Student { int id; char name[20]; float score; }; int main() { // 寫入結(jié)構(gòu)體 std::ofstream out("student.bin", std::ios::out | std::ios::binary); Student s1 = {1001, "Alice", 95.5f}; out.write(reinterpret_cast<const char*>(&s1), sizeof(s1)); out.close(); // 讀取結(jié)構(gòu)體 std::ifstream in("student.bin", std::ios::in | std::ios::binary); Student s2; in.read(reinterpret_cast<char*>(&s2), sizeof(s2)); in.close(); std::cout << "ID: " << s2.id << ", 姓名: " << s2.name << ", 成績(jī): " << s2.score << std::endl; return 0; }
注意:結(jié)構(gòu)體中若包含指針或STL容器(如std::string),不能直接用 write/read 讀寫,需序列化處理。
基本上就這些。掌握 read() 和 write() 配合 reinterpret_cast 與 sizeof,就能高效操作二進(jìn)制文件。以上就是c++++中如何讀寫二進(jìn)制文件_c++二進(jìn)制文件I/O操作示例的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
c++怎么學(xué)習(xí)?c++怎么入門?c++在哪學(xué)?c++怎么學(xué)才快?不用擔(dān)心,這里為大家提供了c++速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)