2013-04-30 82 views
0

我正在嘗試讀取存儲在HGT文件中的海拔數據。據我所知,他們可以讀作二進制文件。如何讀取C++中的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; 
} 

第一次運行後,它給了我一串零,並沒有什麼else:| hgt文件很好,我用一個可以讀取幾種類型的地圖文件的應用程序進行測試,它包含我需要的高程數據。

+0

您只從文件中讀取總共2個字節。您需要爲陣列中的每個位置讀取2個字節。數組大小的第二維中也有一個錯字。 – 2013-04-30 10:33:19

+0

我在猜測同樣的事情,但你能幫我解讀整個文件嗎?或如何讀取特定的線/像素位置? – 2013-04-30 10:35:27

回答

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

我在答案中增加了一個例子。該文件基本上只是磁盤上的一個數組,因此您需要查找適當的行,並在此處讀取值。 – 2013-04-30 23:55:41

+0

非常感謝你,這是我需要的一切:) – 2013-05-02 10:40:00