1.下载eccodes
下载网址:
Releases - ecCodes - ECMWF Confluence Wikihttps://confluence.ecmwf.int/display/ECC/Releases
因为它对cmake版本有要求,如果版本不匹配,可以适当选择可匹配的包或更换cmake的版本。本文使用的是eccodes是2.36.4版本,cmake使用的是2.8.12.2版本。
2. 解压并安装
执行如下命令:
mkdir /home/grib/griblib/
tar -xzf eccodes-x.y.z-Source.tar.gz
mkdir build ; cd build
cmake -DCMAKE_INSTALL_PREFIX=/home/grib/griblib/ ../eccodes-2.36.4-Source
make
ctest
make install
安装完成后,生成的动态库会放在/home/grib/griblib/目录下。
3.测试
下面的代码是读取安装包里的测试文件reduced_latlon_surface.grib1的测试程序,文件名是read_grib.cpp。
#include <stdio.h>
#include <stdlib.h>
#include "eccodes.h"
int main(int argc, char** argv)
{
int err = 0;
size_t i = 0;
FILE* in = NULL;
const char* filename = "../../data/reduced_latlon_surface.grib1";
codes_handle* h = NULL;
long numberOfPoints = 0;
const double missing = 1.0e36;
double *lats, *lons, *values; /* arrays */
in = fopen(filename, "rb");
if (!in) {
fprintf(stderr, "Error: unable to open input file %s\n", filename);
return 1;
}
/* create new handle from a message in a file */
h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);
if (h == NULL) {
fprintf(stderr, "Error: unable to create handle from file %s\n", filename);
return 1;
}
CODES_CHECK(codes_get_long(h, "numberOfPoints", &numberOfPoints), 0);
CODES_CHECK(codes_set_double(h, "missingValue", missing), 0);
lats = (double*)malloc(numberOfPoints * sizeof(double));
if (!lats) {
fprintf(stderr, "Error: unable to allocate %ld bytes\n", (long)(numberOfPoints * sizeof(double)));
return 1;
}
lons = (double*)malloc(numberOfPoints * sizeof(double));
if (!lons) {
fprintf(stderr, "Error: unable to allocate %ld bytes\n", (long)(numberOfPoints * sizeof(double)));
free(lats);
return 1;
}
values = (double*)malloc(numberOfPoints * sizeof(double));
if (!values) {
fprintf(stderr, "Error: unable to allocate %ld bytes\n", (long)(numberOfPoints * sizeof(double)));
free(lats);
free(lons);
return 1;
}
CODES_CHECK(codes_grib_get_data(h, lats, lons, values), 0);
for (i = 0; i < numberOfPoints; ++i) {
if (values[i] != missing) {
printf("%f %f %f\n", lats[i], lons[i], values[i]);
}
}
free(lats);
free(lons);
free(values);
codes_handle_delete(h);
fclose(in);
return 0;
}
运行如下命令:
g++ read_grib.cpp -I /home/grib/griblib/include/ -o read_grib -L /home/grib/griblib/lib -l eccodes
可以生成read_grib可执行文件。需要注意的是,上面的安装时生成的动态库文件名为libeccodes.so,但在编译命令中引用的是eccodes,不需要lib前缀和扩展名。
执行如下命令:
./read_grib
可以读取并显示文件中的内容。