如何在C ++中阅读HGT文件

时间:2013-04-30 10:21:35

标签: c++ file binary elevation .hgtags

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

我找到了这个帖子:
How do I access .HGT SRTM files in C++?

根据该帖子,我的示例代码是:

#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文件很好,我用一个可以读取几种类型的地图文件的应用程序测试它,它包含我需要的高程数据。

1 个答案:

答案 0 :(得分:2)

这将读取文件并正确填充数组。一次读取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;
}