Skip to content

Instantly share code, notes, and snippets.

@simonrw
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save simonrw/9646085 to your computer and use it in GitHub Desktop.

Select an option

Save simonrw/9646085 to your computer and use it in GitHub Desktop.
Quick file to read the floating point magnitude column from a strangely formatted fits file
all: read_fits
read_fits: read_fits.c
gcc $< -o $@ -lcfitsio -Wall -Wextra
#include <stdio.h>
#include <fitsio.h>
#include <assert.h>
void fits_error(int status) {
if (status) {
fits_report_error(stderr, status);
exit(status);
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <fitsfile>\n", argv[0]);
return 1;
}
const char *infile = argv[1];
int status = 0;
fitsfile *fptr;
fits_open_file(&fptr, infile, READONLY, &status);
fits_error(status);
int hdutype = 0;
fits_movabs_hdu(fptr, 2, &hdutype, &status);
fits_error(status);
assert(hdutype == ASCII_TBL);
int colnum = 0;
fits_get_colnum(fptr, CASEINSEN, "Jmag", &colnum, &status);
fits_error(status);
printf("Found Jmag column at index %d\n", colnum);
long nrows = 0;
fits_get_num_rows(fptr, &nrows, &status);
fits_error(status);
printf("%ld rows\n", nrows);
int typecode = 0;
long repeat = 0;
long width = 0;
fits_get_coltype(fptr, colnum, &typecode, &repeat, &width, &status);
fits_error(status);
printf("Data type %d, repeat %ld, width %ld\n", typecode, repeat, width);
float *data = malloc(nrows * sizeof(float));
fits_read_col(fptr, typecode, colnum, 1, 1, nrows, 0, data, 0, &status);
fits_error(status);
/* Print the first 5 elements */
int i = 0;
for (i = 0; i < 5; i++) {
printf("Element %d, value %f\n", i, data[i]);
}
free(data);
fits_close_file(fptr, &status);
fits_error(status);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment