首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C++中读取HGT文件

如何在C++中读取HGT文件
EN

Stack Overflow用户
提问于 2013-04-30 18:21:35
回答 1查看 3.2K关注 0票数 0

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

我找到了这个帖子:

How do I access .HGT SRTM files in C++?

基于这篇文章,我的示例代码是:

代码语言:javascript
复制
#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文件很好,我用一个可以读取几种类型的地图文件的应用程序对它进行了测试,它包含了我需要的高程数据。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-30 19:39:45

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

我将height数组移出了main,以避免在Visual Studio中使用默认堆栈大小时出现堆栈溢出问题。如果您的堆栈足够大,您可以将其移回,或者在堆上动态分配内存。

代码语言:javascript
复制
#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;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16297540

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档