sgetn"覆盖"一个const参数

时间:2015-01-29 06:40:29

标签: c++ file buffer

std::vector<std::bitset<8>>& vecBin

如果vecBin恰好有4个元素,则会发生以下情况:

bool BinFinder::containsInFile(const std::vector<std::bitset<8>>& vecBin, uint fails/* = 1*/)
{
    if (fails >= vecBin.size()) return true;

    file.open(path, std::ifstream::binary);
    if ((file.rdstate() & std::ifstream::failbit ) != 0)
        exit(EXIT_FAILURE);

    // Reading blocks of 4 KiB (MBLOCK_SIZE = 4096 Bytes)
    //file.read(buff, MBLOCK_SIZE);
    bool found {};
    uint bytesRead { 1 }, foundAtJ {}, failed {};
    while(/*file.good()*/!file.eof() && !found && bytesRead > 0)
    {
        failed = 0;

        // Reading blocks until 4 KiB (MBLOCK_SIZE = 4096 Bytes)
        //bytesRead = file.rdbuf()->sgetn(buff, MBLOCK_SIZE);
        std::streambuf *sb = file.rdbuf();  //debug

        std::cout << "After rdbuf" << std::endl;    //debug
        for (auto i = 0; i < vecBin.size(); ++i)    //debug
            std::cout << vecBin.at(i) << std::endl; //debug

        bytesRead = sb->sgetn(buff, MBLOCK_SIZE);   //debug

        std::cout << "After sgetn" << std::endl;    //debug
        for (auto i = 0; i < vecBin.size(); ++i)    //debug
            std::cout << vecBin.at(i) << std::endl; //debug


...

在调用sgetn(buff,MBLOCK_SIZE)之后,就像这个调用覆盖了vecBin sice的内容一样,这个代码片段的输出是:

output After rdbuf 01100010 01100011 01110101 10101010 After sgetn 00110011 00001010 01101111 10101010

为什么sgetn正在修改vecBin的内容?!

1 个答案:

答案 0 :(得分:0)

sgetn将从其关联的流缓冲区中获取字符,并将它们存储在您传递的数组中。由于您的代码不包含buff的任何类型的定义,因此假定它是vecBin内容的别名,解释了为什么vecBin会被更改...