Creating FITS files in c++

A simple example, very similar to that given in the CFITSIO guidebook, on how to create a FITS file using CFITSIO. In this case I’m also building against some casacore libraries, but these aren’t going to be used in this little code snippet but the idea is to use casacore todo further analysis. I’m hoping to post more here over time. Anyway the code (this can also be found as a filebuild_fits.cpp:

/* Create a FITS file, using cfitsio and some casacore libraries
by Samuel George
Compile: g++ build_fits.cpp -o build_fits -lcasa_casa -lcfitsio
#include // STL iostream
extern “C”{
using std::cerr;
using std::cout;
using std::endl;
using std::string;
int main()
cout << "Create a FITS file" << endl;
int lenTime(10), status (0), lenFreq(20);
long naxis(2), naxes[2] = {lenTime,lenFreq};
long nelements (lenTime*lenFreq);
long fpixel (1), exposure (1500);
char comment[] ="Total Exposure Time";
cout << comment << endl;
float pixels[lenFreq][lenTime];
// create an array of pixels
try {
for (int ii(0); ii < lenTime; ii++){
for (int jj(0); jj <lenFreq; jj++){
pixels[jj][ii] = 10.0*(ii+jj);
} catch (string message) {
cerr << "Error creating pixel array" << message << endl;
try { // write the image to a fits file…
fitsfile *fptr;
fits_create_file (&fptr, "!output.fits", &status);
fits_create_img (fptr, FLOAT_IMG,naxis,naxes,&status);
/* Write a keyword – its the address you pass */
//write an array to the image
fits_write_img(fptr, TFLOAT, fpixel, nelements, pixels[0],&status);
status = 0 ;
} catch (std::string message) {
cerr << message << endl;

Save the code and compile like so:
g++ build_fits.cpp -o build_fits -lcasa_casa -lcfitsio
and then run with ./build_fits


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: