在 C++ 中读取 .dat 二进制文件(深度图)

Read .dat binary file in c++ (depth map)

我对使用二进制文件还很陌生,所以我不知道如何正确使用这些文件。

我收到了一个 .dat 文件。我知道这是一张深度图——“深度图是一个写入二进制文件的双精度数组,每个数字的大小为 64 位。 数组是逐行写的,数组的维度是Width * Height,行高乘以元素的Width。该文件包含:高度、宽度、数据数组。"

我不会读双字符和做数组。我有这个代码:

ifstream ifs(L"D:\kek\DepthMap_10.dat", std::ios::binary);
char buff[1000];
ifs.seekg(0, std::ios::beg);
int count = 0;

while (!ifs.eof()) {
    ifs.read(buff, 1000);
    cout << count++ << buff<< endl;
}

作为输出我有这样的东西

914 fф╦┼p@)щ↓p╧┬p@уЖФНВ┐p@уTхk↔╝p@юS@∟x╕p@УбХоЗ┤p@☺пC7b░p@лБy>%мp@y ‼i∟сзp@╚_-

我应该怎么做才能将其转换为 double 并接收数组?

P.S。您可以下载文件 here(google 磁盘)。

您不能使用>>读取二进制数据。您需要使用 ifs.read。还有不同的浮点格式,但我假设您和地图的创建者很幸运能够共享相同的格式。

这是一个如何完成的示例:

#include <climits>
#include <fstream>
#include <iostream>
#include <vector>

int main() {
    // make sure our double is 64 bits:
    static_assert(sizeof(double) * CHAR_BIT == 64);

    // ios::binary is not really needed since we use unformatted input with
    // read()
    std::ifstream ifs("DepthMap_10.dat", std::ios::binary);
    if(ifs) {
        double dheight, dwidth;

        // read height and width directly into the variables:
        ifs.read(reinterpret_cast<char*>(&dheight), sizeof dheight);
        ifs.read(reinterpret_cast<char*>(&dwidth), sizeof dwidth);

        if(ifs) { // still ok?
            // doubles are strange to use for sizes that are integer by nature:
            auto height = static_cast<size_t>(dheight);
            auto width = static_cast<size_t>(dwidth);

            // create a 2D vector to store the data:
            std::vector<std::vector<double>> dmap(height,
                                                  std::vector<double>(width));

            // and read all the data points in the same way:
            for(auto& row : dmap) {
                for(double& col : row)
                    ifs.read(reinterpret_cast<char*>(&col), sizeof col);
            }

            if(ifs) {     // still ok?
                // print the map
                for(auto& row : dmap) {
                    for(double col : row) std::cout << col << ' ';
                    std::cout << '\n';
                }
            }
        }
    }
}