3

I'm attempting an application that uses binary data from ".hgt" formatted file. I found a soltuion in C++, but I can't figure out how to translate that solution to C. Each value in the file is type signed short int and there are 1201x1201 values.

const int SIZE = 1201;
signed short int matrix[SIZE][SIZE] = {0};

int main(int argc, const char * argv[])
{
    using namespace std;

    ifstream file("N49E013.hgt", ios::in|ios::binary);    

    unsigned char buffer[2];
    for (int i = 0; i < SIZE; ++i)
    {
        for (int j = 0; j < SIZE; ++j) 
        {
            if(!file.read( reinterpret_cast<char*>(buffer), sizeof(buffer) ))
            {
                cout << "Error reading file!" << endl;
                system("PAUSE");
                return -1;
            }
            matrix[i][j] = (buffer[0] << 8) | buffer[1];       
        }
    }
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
Petr Šrámek
  • 435
  • 7
  • 26

3 Answers3

7

Mainly, you simply need to swap out the std methods for the stdio.h functions, as follows:

#include <stdio.h>

#define SIZE 1201
signed short int matrix[SIZE][SIZE] = {0};

int main(int argc, const char * argv[])
{
    FILE *fp = fopen("N49E013.hgt", "rb");    

    unsigned char buffer[2];
    for (int i = 0; i < SIZE; ++i)
    {
        for (int j = 0; j < SIZE; ++j) 
        {
            if (fread(buffer, sizeof(buffer), 1, fp) != 1)
            {
                printf("Error reading file!\n");
                system("PAUSE");
                return -1;
            }
            matrix[i][j] = (buffer[0] << 8) | buffer[1];       
        }
    }

    fclose(fp);
}
Carey Gregory
  • 6,836
  • 2
  • 26
  • 47
  • 2
    The correct approach to check if `fread()` succeeded is `fread(buffer, sizeof(buffer), 1, fp) < 1`, by the way. –  Dec 27 '13 at 22:00
  • Thanks to both of you for help. – Petr Šrámek Dec 27 '13 at 22:08
  • @H2CO3 In practice the return value on error or eof is 0, so that's just an old (bad) habit. But you're right that the return value not equaling the count parameter is the documented error/eof indicator. +1 and code fixed accordingly. – Carey Gregory Dec 27 '13 at 23:27
1

0) At the top

#include <stdio.h>

1) Remove the inline declarations and move them to the top after main(){

2) Remove the using namespace

3) Replace ifstream ... with

FILE* file = fopen("N49E013.hgt", "rb");

4) Replace file.read... with

fread(buffer, 2, 1, file);

5) Replace cout ... with

printf("Error reading file\n");

6) After the } for the loop, add

fclose(file);
cup
  • 7,589
  • 4
  • 19
  • 42
0

The C code is very similar, you just have to use stdio.h's fopen and fread instead.

See this example: http://www.codingunit.com/c-tutorial-binary-file-io