简体   繁体   English

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

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

I want to binary read a photo in 1460 bytes increments and compare consecutive packets for corrupted transmission.我想以 1460 字节为增量二进制读取一张照片,并比较连续的数据包是否有损坏的传输。 I have a python script that i wrote and want to translate in C++, however I'm not sure that what I intend to use is correct.我有一个 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

I have found int fseek ( FILE * stream, long int offset, int origin );我找到了int fseek ( FILE * stream, long int offset, int origin ); but it's unclear if it reads the first byte that is located offset away from origin or everything in between.但目前尚不清楚它是读取位于offset origin的第一个字节还是介于两者之间的所有字节。

Thanks for clarifications.感谢您的澄清。

#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;
}

This is the code i have so far which doesn't work.这是我到目前为止不起作用的代码。

fseek

doesn't read, it just moves the point where the next read operation should begin.不读取,它只是移动下一个读取操作应该开始的点。 If you read the file from start to end you don't need this.如果您从头到尾阅读文件,则不需要此文件。

To read binary data you want the aptly named std::istream::read .要读取二进制数据,您需要恰当命名的std::istream::read You can use it like this wih a fixed size buffer:您可以像这样使用固定大小的缓冲区:

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM