[英]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.