eccodes/examples/C/grib_get_keys.c

56 lines
1.3 KiB
C
Raw Normal View History

2013-03-25 12:04:10 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "eccodes.h"
2013-03-25 12:04:10 +00:00
2014-06-18 16:14:01 +00:00
int main(int argc, char** argv)
{
2020-01-22 14:57:43 +00:00
int err = 0;
2022-12-29 17:30:01 +00:00
float* values = NULL;
2020-01-22 14:57:43 +00:00
size_t values_len = 0;
size_t i = 0, len = 0;
2020-01-22 14:57:43 +00:00
double average = 0;
2013-03-25 12:04:10 +00:00
2020-01-22 14:57:43 +00:00
FILE* in = NULL;
2022-12-29 17:30:01 +00:00
const char* filename = "../../data/sample.grib2";
2020-01-22 14:57:43 +00:00
codes_handle* h = NULL;
2013-03-25 12:04:10 +00:00
2020-01-22 14:57:43 +00:00
in = fopen(filename, "rb");
if (!in) {
2020-05-14 19:21:31 +00:00
fprintf(stderr, "Error: unable to open file %s\n", filename);
return 1;
}
2013-03-25 12:04:10 +00:00
/* create new handle from the first message in the file*/
2015-02-12 17:34:01 +00:00
h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);
if (h == NULL) {
2020-05-14 19:21:31 +00:00
fprintf(stderr, "Error: unable to create handle from file %s\n", filename);
return 1;
}
fclose(in);
2013-03-25 12:04:10 +00:00
/* get the size of the values array*/
2020-01-22 14:57:43 +00:00
CODES_CHECK(codes_get_size(h, "values", &values_len), 0);
2013-03-25 12:04:10 +00:00
2022-12-29 17:30:01 +00:00
values = (float*)malloc(values_len * sizeof(float));
2013-03-25 12:04:10 +00:00
/* get data values*/
2022-12-29 17:30:01 +00:00
CODES_CHECK(codes_get_float_array(h, "values", values, &values_len), 0);
2013-03-25 12:04:10 +00:00
average = 0;
2022-12-29 17:30:01 +00:00
for (i = 0; i < values_len; i++){
//printf("%f\n",values[i]);
average += values[i];
2022-12-29 17:30:01 +00:00
}
2013-03-25 12:04:10 +00:00
2020-01-22 14:57:43 +00:00
average /= (double)values_len;
2013-03-25 12:04:10 +00:00
free(values);
2020-01-22 14:57:43 +00:00
printf("There are %d values, average is %g\n", (int)values_len, average);
2013-03-25 12:04:10 +00:00
codes_handle_delete(h);
return 0;
2013-03-25 12:04:10 +00:00
}