/* File: write_geogrid.c Sample subroutine to write an array into the geogrid binary format. Notes: Depending on the compiler and compiler flags, the name of the write_geogrid() routine may need to be adjusted with respect to the number of trailing underscores when calling from Fortran. Michael G. Duda, NCAR/MMM */ #include #include #include #ifdef _UNDERSCORE #define write_geogrid write_geogrid_ #endif #ifdef _DOUBLEUNDERSCORE #define write_geogrid write_geogrid__ #endif #define BIG_ENDIAN 0 #define LITTLE_ENDIAN 1 int write_geogrid( char * fname, /* The name of the file to write */ int * len, /* The length of the filename */ float * rarray, /* The array to be written */ int * nx, /* x-dimension of the array */ int * ny, /* y-dimension of the array */ int * nz, /* z-dimension of the array */ int * isigned, /* 0=unsigned data, 1=signed data */ int * endian, /* 0=big endian, 1=little endian */ float * scalefactor, /* value to divide array elements by before truncation to integers */ int * wordsize ) /* number of bytes to use for each array element */ { char cfname[1024]; int i, narray; int A2, B2; int A3, B3, C3; int A4, B4, C4, D4; unsigned int * iarray; unsigned char * barray; FILE * bfile; narray = (*nx) * (*ny) * (*nz); iarray = (unsigned int *)malloc(sizeof(int) * narray); barray = (unsigned char *)malloc(sizeof(unsigned char) * narray * (*wordsize)); /* Scale real-valued array by scalefactor and convert to integers */ for (i=0; i> 8) & 0xff); barray[(*wordsize)*i+B2] = (unsigned char)( iarray[i] & 0xff); } break; case 3: for(i=0; i> 16) & 0xff); barray[(*wordsize)*i+B3] = (unsigned char)((iarray[i] >> 8) & 0xff); barray[(*wordsize)*i+C3] = (unsigned char)( iarray[i] & 0xff); } break; case 4: for(i=0; i> 24) & 0xff); barray[(*wordsize)*i+B4] = (unsigned char)((iarray[i] >> 16) & 0xff); barray[(*wordsize)*i+C4] = (unsigned char)((iarray[i] >> 8) & 0xff); barray[(*wordsize)*i+D4] = (unsigned char)( iarray[i] & 0xff); } break; } strncpy(cfname, fname, *len); cfname[*len] = '\0'; /* Write array to file */ bfile = fopen(cfname,"wb"); fwrite(barray,sizeof(unsigned char),narray*(*wordsize),bfile); fclose(bfile); free(iarray); free(barray); return 0; }