C++以二进制流的形式读取文件,在中间随机跳过字节

C++ reading file in as binary stream, skipping byte, randomly, in middle

本文关键字:在中间 随机 字节 文件 读取 二进制 C++      更新时间:2023-10-16
std::ifstream infile;
infile.open(fullfilename, std::ios::binary);
std::vector<unsigned char> byteVect;
if (!infile.fail()) {
    infile.seekg(0, std::ios_base::end);
    int flsz = infile.tellg();
    LOG("sz=%d, infile.fail() returned %d", flsz, infile.fail());
    infile.seekg(0, std::ios_base::beg);
    while (!infile.eof()) {
        unsigned char byte;
        infile >> byte;
        if (infile.fail()) break;
        byteVect.push_back(byte);
    }
    infile.close();
    LOG("Loaded %d bytes into buffer", byteVect.size());

然后,我使用我最喜欢的自制库函数将缓冲区记录到 logcat。很多零,但它仍然是早期的门。

问题是并非所有字节都以这种方式读取。我在流中间发现一个缺少的字节,它再见成功反序列化。我知道并非所有字节都被读取,因为有时(每当它失败时(flsz的第一个日志比下一个byteVect.size()日志多一个。我知道它发生在中间,因为我正在观看输入和输出的十六进制转储(权力的游戏不是(。

我看不出我的代码有什么问题,但我以前只是坚持 C 风格fopen fread fwrite但认为是时候发展了。我相信你会在我的循环算法中找到一百万个洞,但我正在学习。谢谢和东西。

这段代码有很多问题。主要的是循环eof()通常是错误的(请参阅这篇文章(,对于二进制输入,您不应该使用 >> .应使用read()(引用(,因为>>会跳过空格,并且可能会更改行结束字符。

以下是我将如何完成此任务:

int main()
{
    std::vector<unsigned char> byteVect;
    std::ifstream infile;
    // open file at the end (to get its length)
    infile.open("test.txt", std::ios::binary|std::ios::ate);
    if(!infile.is_open())
    {
        std::cerr << "Error opening file: " << "" << std::endl;
        return 1;
    }
    // tellg() gives is the file position
    // (and therefore length)
    byteVect.resize(infile.tellg()); // make our vector big enough
    if(!byteVect.empty())
    {
        infile.seekg(0); // move file position back to beginning
        if(!infile.read((char*)&byteVect[0], byteVect.size()))
        {
            std::cerr << "Error reading file: " << "" << std::endl;
            return 1;
        }
    }
    infile.close();
    std::cout << "Loaded " << byteVect.size() << " bytes into vector." << 'n';
}