0

我正在尝试读取存储在 HGT 文件中的高程数据。据我所知,它们可以作为二进制文件读取。

我找到了这个线程:
如何在 C++ 中访问 .HGT SRTM 文件?

根据那篇文章,我的示例代码是:

#include <iostream>
#include <fstream>

int main(int argc, const char * argv[])
{

std::ifstream::pos_type size;
char * memblock;

std::ifstream file ("N45W066.hgt", std::ios::in|std::ios::binary|std::ios::ate);

if (file.is_open())
{
    size = 2;
    memblock = new char [size];

    file.seekg(0, std::ios::beg);
    file.read(memblock, size);

    int srtm_ver = 1201;
    int height[1201][1021];

    for (int i = 0; i<srtm_ver; ++i){
        for (int j = 0; j < srtm_ver; ++j) {

            height[i][j] = (memblock[0] << 8 | memblock[1]);
            std::cout<<height[i][j]<<" ";
        }
        std::cout<<std::endl;
    }
}


return 0;
}

第一次运行后,它给了我一堆零,没有别的:| hgt 文件很好,我已经使用可以读取多种类型地图文件的应用程序对其进行了测试,它包含我需要的高程数据。

4

1 回答 1

3

这将读取文件并正确填充数组。一次读取 2 个字节通常不是最有效的方法,但它很简单。另一种方法是读取整个文件,然后交换字节。

我将高度数组移到 main 之外,以避免 Visual Studio 中默认堆栈大小的堆栈溢出问题。如果您的堆栈足够大,您可以将其移回,或在堆上动态分配内存。

#include <iostream>
#include <fstream>

const int SRTM_SIZE = 1201;
short height[SRTM_SIZE][SRTM_SIZE] = {0};

int main(int argc, const char * argv[])
{
    std::ifstream file("N45W066.hgt", std::ios::in|std::ios::binary);
    if(!file)
    {
        std::cout << "Error opening file!" << std::endl;
        return -1;
    }

    unsigned char buffer[2];
    for (int i = 0; i < SRTM_SIZE; ++i)
    {
        for (int j = 0; j < SRTM_SIZE; ++j) 
        {
            if(!file.read( reinterpret_cast<char*>(buffer), sizeof(buffer) ))
            {
                std::cout << "Error reading file!" << std::endl;
                return -1;
            }
            height[i][j] = (buffer[0] << 8) | buffer[1];
        }
    }

    //Read single value from file at row,col
    const int row = 500;
    const int col = 1000;
    size_t offset = sizeof(buffer) * ((row * SRTM_SIZE) + col);
    file.seekg(offset, std::ios::beg);
    file.read( reinterpret_cast<char*>(buffer), sizeof(buffer) );
    short single_value = (buffer[0] << 8) | buffer[1];
    std::cout << "values at " << row << "," << col << ":" << std::endl;
    std::cout << "  height array: " << height[row][col] << ", file: " << single_value << std::endl;

    return 0;
}
于 2013-04-30T11:39:45.133 回答