How to read HGT files in C++

2019-04-02 21:41发布

问题:

I'm trying to read the elevation data stored in HGT files. As far as I know they can be read as binary files.

I found this thread:
How do I access .HGT SRTM files in C++?

Based on that post, my sample code is:

#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;
}

After the first run, it gives me a bunch of zeros, and nothing else :| The hgt file is good, i've tested it with an application that can read several type of map files, and it contains the elevation data what i need.

回答1:

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;
}