Skip Navigation Links 
NOAA logo - Click to go to the NOAA home page National Weather Service   NWS logo - Click to go to the NWS home page
Climate Prediction Center

About Us
   Our Mission
   Who We Are

Contact Us
   CPC Information
   CPC Web Team

HOME > Monitoring_and_Data > Oceanic and Atmospheric Data > Reanalysis: Atmospheric Data > wgrib2 calling wgrib2 from C

wgrib2: Calling wgrib2 from C


Calling wgrib2 from C can be as simple as calling the system function

    system("wgrib2 IN.grb -match ":TMP:2 m above ground:anl:" -csv tmp2m.csv"); 
You can also use wgrib2 as an filter. For example, the main program has grib data and it wants the data regridded or converted into netcdf.
#include <stdio.h>
#include <stdlib.h>

 * how to call wgrib2 from a C program.
 * in this example, the main program writes grib data to a pipe, 
 * wgrib2 reads from the pipe, regrids the data and saves in a file.
 * This example shows how to call wgrib2 from a C program

#define INPUT_FILE  "../examples/gep19.t00z.pgrb2af180"

int main() {

   FILE  *input, *wgrib2_input;
   int c,err;

   /* open a file with "test" data */
   input = fopen(INPUT_FILE,"rb");
   if (input == NULL) exit(1);

   /* run wgrib2 to read from stdin and interpolate to a new grid */

   wgrib2_input = popen("wgrib2 - -new_grid_winds earth -new_grid ncep grid 221 out.221.grb","w");
   if (wgrib2_input == NULL) exit(2);

   while ( (c = fgetc(input))  != EOF) {
	fputc(c, wgrib2_input);

   /* close the wgrib2 program */
   printf("all done, err=%d\n",err);

   return 0;

NOAA/ National Weather Service
National Centers for Environmental Prediction
Climate Prediction Center
5830 University Research Court
College Park, Maryland 20740
Climate Prediction Center Web Team
Page last modified: May 15, 2005
Disclaimer Privacy Policy