【问题标题】:Read .dat binary file in c++ (depth map)在 C++ 中读取 .dat 二进制文件(深度图)
【发布时间】:2021-12-18 23:56:31
【问题描述】:

我对使用二进制文件非常陌生,所以我不知道如何正确使用此类文件。

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

我不知道如何读取双字符并创建一个数组。我有这个代码:

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@╚_-

我应该怎么做才能把它转换成双精度并接收一个数组?

附:您可以下载文件here(谷歌磁盘)。

【问题讨论】:

标签: c++ arrays binary


【解决方案1】:

您不能使用&gt;&gt; 来读取二进制数据。您需要使用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';
                }
            }
        }
    }
}

【讨论】:

  • 非常感谢!它对我理解我应该如何使用它有很大帮助。
  • @Daria 很高兴听到这个消息!不客气!
猜你喜欢
  • 2015-06-27
  • 2012-08-01
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 2011-09-03
相关资源
最近更新 更多