unload_text.h
1//-*-C++-*-
2/***************************************************************************
3 *
4 * Copyright (C) 2009 by Willem van Straten
5 * Licensed under the Academic Free License version 2.1
6 *
7 ***************************************************************************/
8
9// psrchive/Base/Formats/PSRFITS/unload_text.h
10
11#ifndef __unload_text_h
12#define __unload_text_h
13
14#include "FITSError.h"
15#include "FilePtr.h"
16
17#include <fitsio.h>
18#include <string.h>
19#include <vector>
20#include <iostream>
21
22template<class T>
23void unload_text (fitsfile* fptr, const char* table, const char* column,
24 const T* instance, bool verbose = false)
25{
26 // Move to the HDU named table
27 int status = 0;
28 fits_movnam_hdu (fptr, BINARY_TBL, const_cast<char*>(table), 0, &status);
29
30 if (status)
31 throw FITSError (status, "unload_text",
32 "fits_movnam_hdu %s", table);
33
34 int colnum = 0;
35 fits_get_colnum (fptr, CASEINSEN, const_cast<char*>(column),
36 &colnum, &status);
37
38 int typecode = 0;
39 long repeat = 0;
40 long width = 0;
41
42 fits_get_coltype (fptr, colnum, &typecode, &repeat, &width, &status);
43
44 if (typecode != TSTRING)
45 throw Error (InvalidState, "unload_text",
46 "%s typecode != TSTRING", column);
47
48 FilePtr stream = tmpfile();
49 if (!stream)
50 throw Error (FailedSys, "unload_text", "tmpfile");
51
52 try
53 {
54 instance->unload (stream);
55 }
56 catch (Error& error)
57 {
58 throw error += "unload_text";
59 }
60
61 // seek back to the start of the file
62 fseek (stream, 0, SEEK_SET);
63
64 std::vector<char> text (repeat * 2);
65 char* temp = &(text[0]);
66
67 int row = 0;
68 while (fgets (temp, repeat, stream) == temp)
69 {
70 row ++;
71
72 // get rid of the newline
73 char* newline = strchr (temp, '\n');
74 if (newline)
75 *newline = '\0';
76
77 if (verbose)
78 std::cerr << "unload_text row=" << row << " line='" << temp << "'" << std::endl;
79
80 fits_write_col (fptr, TSTRING, colnum, row, 1, 1, &temp, &status);
81
82 if (status)
83 throw FITSError (status, "unload_text",
84 "fits_write_col row=%d", row);
85 }
86
87 if (verbose)
88 std::cerr << "unload_text wrote " << row << " rows" << std::endl;
89}
90
91#endif

Generated using doxygen 1.14.0