我有一个 C++
应用程序,在其中需要读取二进制文件的某一部分,并将这些字节放入 std::bitset
中。
虽然我能够将正确的文件部分读入 std::string
对象,但如果可以避免的话,我不想使用 unsigned char->std::string->std::bitset
的方法。
有没有直接将文件的一部分读入 bitset 的方法?
到目前为止,我已经有了以下代码(在此示例中,我从位置 64 开始,然后将 128 个字节读入一个 string
,最后初始化了一个 bitset
):
//Open the file
std::ifstream file (path, std::ios::in | std::ios::binary | std::ios::ate);
//Move to the position to start reading
file.seekg(64);
//Read 128 bytes of the file
std::vector<unsigned char> mDataBuffer;
mDataBuffer.resize( 128 ) ;
file.read( (char*)( &mDataBuffer[0]), 128 ) ;
//Read as string (I'm trying to avoid this)
std::string s_data( mDataBuffer.begin(), mDataBuffer.end());
std::bitset<1024> foo (s_data); //8 bits/byte x 128 bytes = 1024 bits
file.close()
std::ios::ate
标志?此外,对于输入流使用ate
标志并没有太多意义,因为如果您不从末尾寻找,就没有可读取的内容。 - Some programmer dudeios:ate
,所以它很可能被错误使用(我不太确定如何使用它)。 - Brett