繁体   English   中英

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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