[英]Reading multiple bytes from file and storing them for comparison in C++
我想以 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.