c++ - 无法读取二进制文件

标签 c++ file io binary binaryfiles

我有一个应该主要包含原始字节数据的二进制文件,该文件在 CubeState 类中生成和处理。我跑了几个测试,似乎写作过程没问题。我遇到的唯一问题是有时它会记下 0x00 字符,每当发生这种情况时,我都会收到裁剪数据或没有数据。这是我如何写/读的例子。

CubeState currentParent = CubeState();
char* buf = new char[10];
std::ofstream ostr = std::ofstream("parents", std::ios::out | std::ios::binary);
ostr.write(currentParent.getContent().c_str(), 10);
ostr.close();

std::ifstream istr("parents", std::ios::in | std::ios::binary);     
istr.read(buf, 10);
istr.close();
currentParent = CubeState(buf);

currentParent.getContent().c_str() 默认形式将返回如下字符串 - 0x00 0x01 0x05 0x0B 0x17 等等。

编辑

CubeState 是正在工作的黑盒子。如果您需要另一个示例 - 给您:

char* buf = new char[4];
std::ofstream ostr = std::ofstream("parents", std::ios::out | 
std::ios::binary);
ostr.write("" + (char)0 + (char)1 + (char)5 + (char)11, 4);
ostr.close();

std::ifstream istr("parents", std::ios::in | std::ios::binary);     
istr.read(buf, 4);
istr.close();
std::cout << buf << std::endl;

输出将为空,如果您在运行时检查 buf - 它也是空的

最佳答案

CubeState 容易生成以/0 开头的输出,即 (char)0。这导致了问题 - 返回的字符串被假定为空。 一旦我有足够的代码片段来正确证明我的担忧,我将在稍后提出另一个问题。 如果您仍然对 CubeState.getContent() 的内容感兴趣 - 就在这里

class CubeState {
private:
state = {
0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26
};
const int av[] = { 0, 0, 1, 1, 0, 2, 2, 3, 3, 4, 0, 5, 0, 0, 0, 6, 0, 7, 4, 8, 5, 9, 0, 10, 6, 11, 7 },
corners[] = { 0, 2, 6, 8, 18, 20, 24, 26 },
sides[] = { 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25 };

... 

std::string getContent() {
std::bitset<80> container(0);
for (int i = 0; i < 8; i++) {
    int temp = av[state[corners[i]]];
    container[i * 3] = temp % 2;
    temp >>= 1;
    container[i * 3 + 1] = temp % 2;
    temp >>= 1;
    container[i * 3 + 2] = temp;
}

for (int i = 0; i < 12; i++) {
    int temp = av[state[sides[i]]];
    container[i * 4 + 24] = temp % 2;
    temp >>= 1;
    container[i * 4 + 25] = temp % 2;
    temp >>= 1;
    container[i * 4 + 26] = temp % 2;
    temp >>= 1;
    container[i * 4 + 27] = temp;
}

int temp = parent;  
container[72] = temp % 2;
temp >>= 1;
container[73] = temp % 2;
temp >>= 1;
container[74] = temp % 2;
temp >>= 1;
container[75] = temp;
std::string result;

for (int i = 0; i < 10; i++) 
    result += std::bitset<8>(container.to_string().substr(i, i * 8)).to_ulong() + 1;

return result;
}

关于c++ - 无法读取二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53792185/

相关文章:

c++, c++11, std::atomic 成员函数

file - Node.js/Express 路由到静态文件 URL

c - 我有一个文件,将其所有内容复制到一个数组中。例如,如何删除第一个字符串或中间字符串?

c - 将文本文件中的一行读取到c中的字符数组中

JavaIO : Memory/Performance issue when reading “last lines” of files using bufferedReader

c++ - 在 OpenCV 中加载像素值数组

c++ - Qt C++ QDataStream读取数字13

c++ - MFC 将消息发送到主线程(而不是窗口)?

c++ - 从 .txt 文件中获取数字并将它们放入 C++ 中的 vector 中

python - 如何保存 Python NLTK 对齐模型供以后使用?