How to read HGT files in C++

情到浓时终转凉″ 提交于 2019-12-03 21:52:14

This will read the file and populate the array correctly. Reading 2 bytes at a time generally isn't the most efficient way to do it, but it is simple. The alternative would be to read the whole file and then swap the bytes afterward.

I moved the height array outside main to avoid a stack overflow issue with the default stack size in Visual Studio. If your stack is large enough you could move it back, or dynamically allocate the memory on the heap.

#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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!