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


There 3 basic ways to call wgrib2 from a C program. The simpler way is to call wgrib2 and when wgrib2 finishes execution, control is returned to the calling program. A more complicated way to run wgrib2 in another process and communicate between the two processes.

Simple: system call

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"); 
This approach is s simple but there is overhead of initializing and running wgrib2 as well as opening and closing of the files.

Simple: wgrib2 as a subroutine

Wgrib2 v2.0.2 introduced the ability to call wgrib2 as a subroutine. This avoids the overhead of loading wgrib2 into memory and minimizes file operations. There is still an overhead of parsing the command line-arguements (once per subroutine call).

    int argc;
    char argv[MAX_ARGC][MAX_STRLEN];
    ierr = wgrib2(argc, argv);
More information is given in callable_wgrib2.

Not so Simple: wgrib2 as a Process

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