从文件中读取多个字节,并将它们存储在C++中进行比较

Reading multiple bytes from file and storing them for comparison in C++

本文关键字:存储 C++ 比较 读取 文件 字节      更新时间:2023-10-16

我想以1460字节为增量二进制读取照片,并比较连续数据包是否存在损坏的传输。我写了一个python脚本,想用C++翻译,但我不确定我打算使用的是正确的。

for i in range(0, fileSize-1):
buff=f.read(1460) // buff stores a packet of 1460 bytes where f is the opened file
secondPacket=''
for j in buff:
secondPacket+="{:02x}".format(j)
if(secondPacket==firstPacket):
print(f'Packet {i+1} identical with {i}')
firstPacket=secondPacket

我找到了int fseek ( FILE * stream, long int offset, int origin );,但不清楚它是读取位于offset远离origin的第一个字节,还是读取两者之间的所有字节。

感谢您的澄清。

#include <iostream>
#include <fstream>
#include <array>
std::array<char, 1460> firstPacket;
std::array<char, 1460> secondPacket;
int i=0;
int main() {
std::ifstream file;
file.open("photo.jpg", std::ios::binary);
while (file.read(firstPacket.data(), firstPacket.size())){
++i;
if (firstPacket==secondPacket)
std::cout<<"Packet "<<i<<" is a copy of packet "<<i-1<<std::endl;
memcpy(&secondPacket, &firstPacket, firstPacket.size());
}
std::cout<<i; //tested to check if i iterate correctly
return 0;
}

这是我目前为止的代码,但它不起作用。

fseek

不读取,它只是移动下一个读取操作应该开始的点。如果你从头到尾都读这个文件,你就不需要这个了。

要读取二进制数据,您需要适当命名的std::istream::read。你可以像这样使用固定大小的缓冲区:

// char is one byte, could also be uint8_t, but then you would need a cast later on
std::array<char, 1460> bytes; 

while(myInputStream.read(bytes.data(), bytes.size())) {
// do work with the read data
}