大文件分块读写需用binary模式、64KB~1MB块大小、std::vector缓冲区,通过seekg/seekp按字节偏移定位,用gcount()校验实际读取量,避免内存溢出与文本模式陷阱。
直接用 std::ifstream::read() 一次性读整个 GB 级文件会触发内存溢出或系统拒绝分配,必须分块。核心是控制每次读取的字节数,并用 seekg() 定位起始位置。
关键点:块大小不是越大越好——通常设为 64KB~1MB(65536 或 1048576),兼顾 I/O 效率与内存安全;避免用 std::string 存原始二进制块,改用 std::vector 或裸 char* 缓冲区。
file.seekg(offset, std::ios::beg) 跳转到指定字节偏移(注意:offset 是 std::streamoff 类型,别用 int)offset += chunk_size,继续下一轮file.gcount() 获取实际读取字节数ofstream.seekp(offset, std::ios::beg) 定位,再 write()
seekg() 和 seekp() 的偏移量单位始终是「字节」,不是字符数、行号或记录数。对文本文件用 std::ios::ate 或 std::ios::end 获取文件大小时,结果也以字节为单位,但要注意:
\r\n 会被当成一个字符处理,seekg() 行为不可靠——必须用 std::ios::binary 模式seekg(0, std::ios::end) 后调 tellg() 才能得到总字节数,但此时文件指针在末尾,后续读需先 seekg(0) 回开头std::streamoff 在 32 位平台可能只有 4 字节,无法表示 >2GB 文件的偏移——编译时确保定义了 _FILE_OFFSET_BITS=64(Linux)或使用支持大文件的 CRT(MSVC 需 /D "_CRT_SECURE_NO_WARNINGS" + 正确链接)下面代码实现从 src.bin 分块拷贝到 dst.bin,每块 1MB,显式控制偏移:
#include#include int main() { std::ifstream src("src.bin", std::ios::binary); std::ofstream dst("dst.bin", std::ios::binary);
const size_t chunk_size = 1048576; std::vectorbuf(chunk_size); src.seekg(0, std::ios::end); std::streamoff total = src.tellg(); src.seekg(0); std::streamoff offset = 0; while (offset zuojiankuohaophpcn total) { size_t to_read = std::min(chunk_size, static_castzuojiankuohaophpcnsize_tyoujiankuohaophpcn(total - offset)); src.read(buf.data(), to_read); size_t actual = static_castzuojiankuohaophpcnsize_tyoujiankuohaophpcn(src.gcount()); dst.write(buf.data(), actual); offset += actual; } return 0; }
注意:
src.gcount()必须在每次read()后立即获取,它反映上一次读操作真实字节数;不能依赖to_read,因为文件可能被并发修改或到达 EOF 边界。seekp 写入时覆盖 vs 追加的陷阱
用
seekp()定位后调write(),行为取决于文件打开方式:
- 用
std::ios::binary打开但没加std::ios::trunc:写入会覆盖对应位置,文件长度不变(除非写到末尾之后,会扩展)- 用
std::ios::app时,seekp()无效——所有写入强制追加到末尾- 想“随机写入”某块数据(如更新 ZIP 中某个文件),必须确保目标文件已存在且足够长(可用
seek预扩展)p(file_size-1); write("\0", 1)
大文件场景下,
seekp()后写入比反复打开/关闭快得多,但务必确认磁盘空间充足——写入失败时不会自动回滚,容易产生半截损坏文件。