0

I'm trying to translate a matlab code which reads an hgt file to c++ and I've come about this resource. However, instead of reading the file by column and row I was wondering if there were any way to use fread to get the desired values faster. The matlab code looks like this:

% ilat and ilon, both vectors, already calculated
% Calculate the offset to each point
offset = ilon*nbytes_per_lon + ilat*2;

% Read the database
path_data = zeros(size(path_lon));
for i = 1:length(path_lon);
    status = fseek(fid, offset(i), 'bof');
    path_data(i)=fread(fid,[1],'integer*2');
end

My c++ code looks like this:

for (i = 0; i < path_lon.size(); i++) {
    offset[i] = ilon[i] * nbytes_per_lon + ilat[i] * 2;
    fseek(pFile, offset[i], SEEK_SET); // SEEK_SET == bof
    path_data[i] = fread(buffer, 2, 1, pFile);
}

The part I'm having trouble converting is the fread portion, on the c++ side it just gives me all 1s. I've read the matlab and c++ documentation for fread but can't seem to properly translate. Any help would be appreciated, thank you!

EDIT: I've gone away with the direct translation and instead am trying to used the linked resource to iterate through the hgt file and get the values that I want. Here's my test code:

std::ifstream::pos_type size = 2;
char* memblock = new char[size];

if(!file) {
    std::cout << "Error opening file!" << std::endl;
    return -1;
}


for (int i = 0; i < SRTM_SIZE; i++) {
    for (int j = 0; j < SRTM_SIZE; j++) {
        height[i][j] = (memblock[0] << 8) | memblock[1];
    }
}


file.seekg(0, std::ios::beg);
file.read(memblock, size);
std::cout << "height at [5][5]: " << height[5][5] << std::endl;
std::cout << "height at [10][10]: " << height[10][10] << std::endl;

The problem I'm having is that both height[5][5] and height[10][10] are giving me the same values (0). What am I doing wrong?

Community
  • 1
  • 1
  • Calling fread that way, isn't it always writing to the first position in the buffer? In case any C++ programmers here try to understand the matlab code, fseek and offset calculation should be clear. The fread call means "read one signed 16 bit integer". Not sure if the C++ call of fread does the same. – Daniel Feb 02 '16 at 00:29
  • 2
    `std::fread` returns the number of objects read successfully, not the data that was read. That ends up in `buffer`. – Baum mit Augen Feb 02 '16 at 00:59
  • Thanks to both of you but I've gone away with the direct translation and am trying to iterate through the hgt file and just reading the values that I want. I've updated the code above to reflect my changes. – brentonang Feb 09 '16 at 05:41
  • Why do you expect different values? Reading your code I expect both to contain `(memblock[0] << 8) | memblock[1];` – Daniel Feb 09 '16 at 11:48

0 Answers0