在C++中进行文件操作时,按固定长度读取数据是一项基础但非常实用的技能。无论是处理二进制文件还是定宽文本,掌握正确的读取方式都能让程序更健壮高效。

使用read方法读取二进制数据
对于二进制文件,最直接的方式是使用ifstream的read成员函数,它可以一次性读取指定长度的字节到内存缓冲区中。
#include <fstream>
#include <iostream>
#include <vector>
int main() {
// 打开二进制文件
std::ifstream file("data.bin", std::ios::binary);
if (!file) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
const int block_size = 16; // 固定读取长度
char buffer[block_size];
while (file.read(buffer, block_size)) {
// 实际读取的字节数
std::streamsize read_count = file.gcount();
// 处理buffer中的数据
std::cout << "读取了 " << read_count << " 字节" << std::endl;
}
file.close();
return 0;
}
上面代码每次从文件读取16字节,gcount()用于获取最后一次读取操作实际读到的字节数,在文件尾部不足固定长度时非常有用。
文本文件中按固定长度读取
如果是文本文件且希望每次读取固定数量字符,同样可以使用read,但需要注意换行符和编码问题。
#include <fstream>
#include <iostream>
int main() {
std::ifstream file("text.txt");
if (!file) {
return 1;
}
const int len = 10;
char buf[len + 1]; // 多留一个位置放结束符
while (file.read(buf, len)) {
buf[len] = ' ';
std::cout << buf << std::endl;
}
// 处理最后一次不足len的情况
std::streamsize last = file.gcount();
if (last > 0) {
buf[last] = ' ';
std::cout << buf << std::endl;
}
file.close();
return 0;
}
使用string和getline的替代方案
有时希望按行但限制最大长度,可以借助getline的第三个参数控制读取字符数。
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream file("log.txt");
std::string line;
while (std::getline(file, line)) {
// 若行过长,只取前20字符
if (line.size() > 20) {
line = line.substr(0, 20);
}
std::cout << line << std::endl;
}
return 0;
}
常见注意事项
- 打开二进制文件时必须加上
std::ios::binary标志,否则在Windows下换行符转换会破坏长度。 - 读取缓冲区要足够大,避免溢出。
- 用
gcount()确认实际读取长度,不要假设每次都读满。
掌握这些按固定长度读取数据的技巧后,处理各类文件格式会更加得心应手。