Simple and Light Interfaces for C and C++ users

SFITSIO User’s Reference Guide
Version 1.2.1 English Edition

CREDITSSOFTWARE DEVELOPMENT:

Chisato Yamauchi
MANUAL DOCUMENT:

Chisato Yamauchi, Ken Ebisawa AND IMC LTD.
MANUAL TRANSLATION:Space Engineering Development Co.,LTD., Sakura Academia Corporation,
KOYOSHOUJI CO.,LTD. AND Yuka Nojo
SPECIAL THANKS:

Daisuke Ishihara, Hajime Baba, Keiichi Matsuzaki, Yukio Yamamoto AND Tomotsugu Goto

Web page: http://www.ir.isas.jaxa.jp/~cyamauch/sli/

SFITSIO is registered as JAXA’s property, and supported by Yamauchi and ISAS/JAXA.

2SFITSIO User’s Reference Guide

Contents
1 Introduction
10
1.1 How long does it take to answer these questions using your favorite FITS I/O library? 10
1.2 Why is SFITSIO being developed? . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3 Why you should use SFITSIO to minimize any programming frustrations . . . . . 13
1.3.1 SFITSIO does not force programmers to learn C++ . . . . . . . . . . . . . 13
1.3.2 You never have to worry about memory leaks with automated memory management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3.3 The API naturally represents the structure of FITS—you will never forget
it once you have used it! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.3.4 Easy random access across multiple HDUs . . . . . . . . . . . . . . . . . . . 14
1.3.5 “High-level API” for type conversion and processing on ZERO, SCALE, and
NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.3.6 ”Low and ultra-low level” API for faster operation . . . . . . . . . . . . . . 15
1.3.7 Image-processing API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.3.8 Functions support variable-length arguments in a printf()-compatible manner 15
1.3.9 Transparent handling of compressed files and files on Web/ftp servers . . . 15
1.3.10 Comment dictionary for the FITS header and FITS template function . . . 15
1.3.11 Super-convenient s++ script . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.3.12 CFITSIO-like, disk-based FITS I/O is also supported . . . . . . . . . . . . 16
1.4 FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2 Installation and Getting Started with SFITSIO
2.1 Supported OS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 Building and installing SFITSIO . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3 Installing multi-threaded compression utilities (optional) . . . . . . . . . . . . . . .
2.4 Operational checks using sample programs . . . . . . . . . . . . . . . . . . . . . . .
2.5 Getting started with SFITSIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19
19
19
20
20
21

3 Review of FITS data structures
3.1 Overall structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Header Unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.3 Image HDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.4 ASCII Table HDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.5 Binary Table HDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22
22
22
23
24
25

4 Representation of FITS data structure using SFITSIO class structure and API 29
4.1 Overview of class structure and access to HDU via API . . . . . . . . . . . . . . . 29
4.2 Structure of FITS header class and header access via API . . . . . . . . . . . . . . 30
4.3 Representation of Image HDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.4 Representation of ASCII Table HDU and Binary Table HDU . . . . . . . . . . . . 31
4.5 System and Notice of FITS Header Management with SFITSIO . . . . . . . . . . . 32
4.6 Our policy when designing member functions . . . . . . . . . . . . . . . . . . . . . 33
4.6.1 API level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.6.2 Rules for arguments and return values . . . . . . . . . . . . . . . . . . . . . 33
4.7 Member functions categorized by their objective and API level . . . . . . . . . . . 33
4.7.1 File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.7.2 Initialization and copying of total content . . . . . . . . . . . . . . . . . . . 34
4.7.3 Swapping the entire content . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.7.4 Aquisition of data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

Ver. 1.2.1

3

4.7.5 Retrieval of the length or size . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7.6 Retrieval of index for internal object array . . . . . . . . . . . . . . . . . . .
4.7.7 Retrieval/configuration of the name or the version of a construct . . . . . .
4.7.8 Data reading (high level) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7.9 Data writing (high level) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7.10 Data reading (low level) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7.11 Data writing (low level) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7.12 Data access (ultra-low level) . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7.13 Conversion between data types . . . . . . . . . . . . . . . . . . . . . . . . .
4.7.14 Member functions that operate on ZERO/SCALE/BLANK/UNIT values .
4.7.15 Data editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7.16 Member functions used to process images . . . . . . . . . . . . . . . . . . .
4.7.17 Member functions of the mdarray class that can be used to edit images . .
4.7.18 Member functions for use in image analysis . . . . . . . . . . . . . . . . . .
4.7.19 Member functions that operate on column definitions of tables . . . . . . .
4.7.20 Special member functions used for processing headers . . . . . . . . . . . .
4.7.21 Member functions used on variable-length arrays in binary tables (low-levelAPIs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

35
36
36
36
37
39
40
41
43
43
44
46
47
47
48
49

5 Tutorial
5.1 First Incantation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2 Read/Write files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.3 Directly accessing remote FITS files via a network . . . . . . . . . . . . . . . . . .
5.4 Read/Write using pipe-connections to make commands (e.g., compression tools) .
5.5 Basis of accessing headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.6 Keyword search in headers (POSIX Extended Regular Expression) . . . . . . . . .
5.7 Editing headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.8 Accessing image data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.9 Creating new FITS image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.10 Copying and pasting image data . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.11 Type conversion and fast access to image data . . . . . . . . . . . . . . . . . . . .
5.12 Collaborations with libwcs of WCSTools . . . . . . . . . . . . . . . . . . . . . . . .
5.13 Collaborations with WCSLIB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.14 Accessing ASCII and binary tables . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.15 Creating binary tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.16 Creating ASCII tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.17 Editing and importing ASCII and binary tables . . . . . . . . . . . . . . . . . . . .
5.18 Editing of HDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

51
51
51
52
53
53
53
54
54
55
55
56
56
58
59
60
61
61
62

6 Things to know before using SFITSIO
6.1 Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.2 NULL and 0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.3 Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.4 Try & catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

63
63
63
63
64

7 Tips on appropriately handling FITS with SFITSIO
7.1 Policies with coding in accordance with the memory management scheme of SFITSIO and hardware selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.2 Tricks for faster operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

66

49

66
66

4

SFITSIO User’s Reference Guide

8 Template Files
8.1 Creating Image HDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.2 Creating Binary Table HDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.3 Specification of SFITSIO template . . . . . . . . . . . . . . . . . . . . . . . . . . .

68
68
69
71

9 Local FITS Extension Compatible with CFITSIO
9.1 Long header value across multiple records . . . . . . . . . . . . . . . . . . . . . . .
9.2 Array of fixed length strings in binary table . . . . . . . . . . . . . . . . . . . . . .
9.3 Writing checksum and datasum . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

73
73
73
73

10 SFITSIO’s Original Extension of FITS
74
10.1 Error Check and Version Management of FITS File by FMTTYPE and FTYPEVER 74
10.2 Distinction of upper and lower case in the header keyword . . . . . . . . . . . . . . 74
10.3 Long keyword in the header (maximum 54 characters) . . . . . . . . . . . . . . . . 74
10.4 Number of columns of the ASCII table or the binary table that exceed 999 . . . . 75
10.5 Applying CONTINUE keyword for long comment string . . . . . . . . . . . . . . . 75
10.6 Definition of new line characters in a string value in FITS header . . . . . . . . . . 75
10.7 Declaration of new column keywords of the ASCII or binary table . . . . . . . . . 76
10.8 Definition of an alias of the ASCII table or the binary table . . . . . . . . . . . . . 76
10.9 Definition of an element name in the column of the binary table . . . . . . . . . . 76
10.10Definition of the number of bits in the column of the binary table . . . . . . . . . . 76
11 Unsupported FITS Standard and Limitation

78

12 Reference
12.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.2 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3 Operation of whole FITS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.1 read stream() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.2 hdus to read().assign(), cols to read().assign() . . . . . . . . . . . . . . . . .
12.3.3 write stream() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.4 access stream() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.5 read template() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.6 stream length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.7 length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.8 fmttype() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.9 ftypever() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.10 hduname(), extname() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.11 hduver(), extver() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.12 hdulevel(), extlevel() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.13 hdutype(), exttype() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.14 index() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.15 init() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.16 append image() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.17 append table() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.18 insert image() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.19 insert table() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.20 erase() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.21 assign fmttype() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.22 assign ftypever() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.23 assign hduname(), assign extname() . . . . . . . . . . . . . . . . . . . . . .

79
79
79
81
81
82
83
84
85
86
86
87
87
87
88
88
89
89
90
91
92
93
94
95
96
97
97

Ver. 1.2.1
12.3.24 assign hduver(), assign extver() . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.25 assign hdulevel(), assign extlevel() . . . . . . . . . . . . . . . . . . . . . . .
12.3.26 hduver is set(), extver is set() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3.27 hdulevel is set(), extlevel is set() . . . . . . . . . . . . . . . . . . . . . . . .
12.4 Operation of header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.1 hdu().header length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.2 hdu().header index() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.3 hdu().header regmatch() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.4 hdu().header().svalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.5 hdu().header().get svalue() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.6 hdu().header().dvalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.7 hdu().header().lvalue(), hdu().header().llvalue() . . . . . . . . . . . . . . . .
12.4.8 hdu().header().bvalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.9 hdu().header().assign(), hdu().header().assignf() . . . . . . . . . . . . . . .
12.4.10 hdu().header().assign() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.11 hdu().header().assign() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.12 hdu().header().assign() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.13 hdu().header().type() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.14 hdu().header().status() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.15 hdu().header().keyword() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.16 hdu().header().get keyword() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.17 hdu().header().value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.18 hdu().header().get value() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.19 hdu().header().comment() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.20 hdu().header().get comment() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.21 hdu().header().assign value() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.22 hdu().header().assign comment() . . . . . . . . . . . . . . . . . . . . . . . .
12.4.23 hdu().header update() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.24 hdu().header assign() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.25 hdu().header init() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.26 hdu().header swap() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.27 hdu().header append records() . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.28 hdu().header append() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.29 hdu().header insert records() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.30 hdu().header insert() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.31 hdu().header erase records() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.32 hdu().header erase() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.33 hdu().header rename() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.34 hdu().header() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.35 hdu().header formatted string() . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.36 hdu().header().get section info() . . . . . . . . . . . . . . . . . . . . . . . .
12.4.37 hdu().header().assign system time() . . . . . . . . . . . . . . . . . . . . . .
12.4.38 hdu().header fill blank comments() . . . . . . . . . . . . . . . . . . . . . . .
12.4.39 hdu().header assign default comments() . . . . . . . . . . . . . . . . . . . .
12.4.40 fits::update comment dictionary() . . . . . . . . . . . . . . . . . . . . . . .
12.5 Operation of header (low-level) and disk-based FITS I/O . . . . . . . . . . . . . .
12.5.1 fits header::read stream() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.5.2 fits header::write stream() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.5.3 fits header::skip data stream() . . . . . . . . . . . . . . . . . . . . . . . . .
12.6 APIs for manipulation of an Image HDU . . . . . . . . . . . . . . . . . . . . . . . .

5
98
98
99
99
101
101
101
102
103
103
104
105
105
105
107
108
109
109
110
111
111
112
112
113
113
114
114
115
116
117
117
118
119
119
120
121
122
122
123
123
124
124
125
126
126
128
128
128
129
130

6

SFITSIO User’s Reference Guide
12.6.1 image().hduname(), image().assign hduname() . . . . . . . . . . . . . . . .
12.6.2 image().hduver(), image().assign hduver() . . . . . . . . . . . . . . . . . . .
12.6.3 image().dim length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.4 image().length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.5 image().type() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.6 image().bytes() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.7 image().col length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.8 image().row length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.9 image().layer length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.10 image().dvalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.11 image().lvalue(), image().llvalue() . . . . . . . . . . . . . . . . . . . . . . . .
12.6.12 image().assign() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.13 image().convert type() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.14 image().bzero(), image().assign bzero() . . . . . . . . . . . . . . . . . . . . .
12.6.15 image().bscale(), image().assign bscale() . . . . . . . . . . . . . . . . . . . .
12.6.16 image().blank(), image().assign blank() . . . . . . . . . . . . . . . . . . . .
12.6.17 image().bunit(), image().assign bunit() . . . . . . . . . . . . . . . . . . . . .
12.6.18 image().init() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.19 image().swap() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.20 image().increase dim() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.21 image().decrease dim() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.22 image().resize() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.23 image().assign default() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.24 image().fix rect args() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.25 image().scan cols() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.26 image().scan rows() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.27 image().scan layers() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.28 image().fill() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.29 image().add() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.30 image().subtract() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.31 image().multiply() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.32 image().divide() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.33 image().fill() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.34 image().copy(), image().cut() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.35 image().paste() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.36 image().add() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.37 image().subtract() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.38 image().multiply() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.39 image().divide() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.40 image().paste() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.41 image().stat pixels() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.42 image().combine layers() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7 APIs for low-level manipulation of an Image HDU . . . . . . . . . . . . . . . . . .
12.7.1 image().data array() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.2 image().data ptr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.3 image().get data() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.4 image().put data() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.5 image().double value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.6 image().float value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.7 image().longlong value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

130
130
131
131
132
132
133
133
133
134
135
135
136
137
138
139
140
140
141
142
142
142
143
144
144
146
147
149
150
151
151
152
153
154
155
156
156
157
157
158
159
160
162
162
162
163
164
165
166
167

Ver. 1.2.1
12.7.8 image().long value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.9 image().short value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.10 image().byte value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.11 image().assign double() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.12 image().assign float() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.13 image().assign longlong() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.14 image().assign long() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.15 image().assign short() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.16 image().assign byte() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8 Manipulation of Ascii Table HDU and Binary Table HDU . . . . . . . . . . . . . .
12.8.1 table().hduname(), table().assign hduname() . . . . . . . . . . . . . . . . .
12.8.2 table().hduver(), table().assign hduver() . . . . . . . . . . . . . . . . . . . .
12.8.3 table().col length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.4 table().row length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.5 table().heap length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.6 table().col index() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.7 table().col name() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.8 table().col().type() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.9 table().col().heap is used() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.10 table().col().heap type() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.11 table().col().bytes() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.12 table().col().elem byte length() . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.13 table().col().elem length() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.14 table().col().dcol length() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.15 table().col().drow length() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.16 table().col().heap bytes() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.17 table().col().max array length() . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.18 table().col().array length() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.19 table().col().definition() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.20 table().col().dvalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.21 table().col().lvalue(), table().col().llvalue() . . . . . . . . . . . . . . . . . . .
12.8.22 table().col().bvalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.23 table().col().svalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.24 table().col().get svalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.25 table().col().assign() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.26 table().col().assign() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.27 table().col().assign() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.28 table().col().convert type() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.29 table().assign null svalue() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.30 table().col().tzero(), table().col().assign tzero() . . . . . . . . . . . . . . . .
12.8.31 table().col().tscal(), table().col().assign tscal() . . . . . . . . . . . . . . . . .
12.8.32 table().col().tnull(), table().col().assign tnull() . . . . . . . . . . . . . . . . .
12.8.33 table().col().tunit(), table().col().assign tunit() . . . . . . . . . . . . . . . .
12.8.34 table().init() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.35 table().col().init() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.36 table().ascii to binary() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.37 table().assign col name() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.38 table().define a col() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.39 table().col header index() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.40 table().col header() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7
168
168
169
170
171
172
172
173
174
176
176
177
177
177
178
178
178
179
179
180
180
180
181
181
182
182
182
182
183
183
184
185
186
188
189
191
192
193
194
195
196
196
197
198
198
199
199
200
200
201

8

SFITSIO User’s Reference Guide
12.8.41 table().update col header() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.42 table().erase col header() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.43 table().rename col header() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.44 table().sort col header() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.45 table().swap() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.46 table().append cols(), table().append a col() . . . . . . . . . . . . . . . . . .
12.8.47 table().insert cols(), table().insert a col() . . . . . . . . . . . . . . . . . . .
12.8.48 table().swap cols() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.49 table().erase cols(), table().erase a col() . . . . . . . . . . . . . . . . . . . .
12.8.50 table().copy() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.51 table().resize rows() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.52 table().append rows(), table().append a row() . . . . . . . . . . . . . . . . .
12.8.53 table().insert rows(), table().insert a row() . . . . . . . . . . . . . . . . . . .
12.8.54 table().erase rows(), table().erase a row() . . . . . . . . . . . . . . . . . . .
12.8.55 table().clean rows() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.56 table().move rows() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.57 table().swap rows() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.58 table().import rows() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.59 table().col().move() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.60 table().col().swap() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.61 table().col().clean() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.62 table().col().import() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.63 table().col().assign default() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9 Lower level manipulation of Ascii Table HDU and Binary Table . . . . . . . . . . .
12.9.1 table().col().data array cs() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.2 table().col().data ptr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.3 table().col().get data() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.4 table().col().put data() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.5 table().heap ptr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.6 table().get heap() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.7 table().put heap() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.8 table().resize heap() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.9 table().reverse heap endian() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.10 table().reserved area length() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.11 table().resize reserved area() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.12 table().col().short value() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.13 table().col().long value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.14 table().col().longlong value() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.15 table().col().byte value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.16 table().col().float value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.17 table().col().double value() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.18 table().col().bit value() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.19 table().col().logical value() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.20 table().col().string value() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.21 table().col().array heap offset() . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.22 table().col().get string value() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.23 table().col().assign short() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.24 table().col().assign long() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.25 table().col().assign longlong() . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.26 table().col().assign byte() . . . . . . . . . . . . . . . . . . . . . . . . . . . .

202
202
203
203
204
204
205
206
206
207
208
208
209
209
210
210
211
211
212
212
213
213
214
215
215
215
216
217
217
218
218
219
219
220
220
220
221
222
223
224
224
225
226
227
228
228
229
230
231
232

Ver. 1.2.1
12.9.27 table().col().assign float() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.28 table().col().assign double() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.29 table().col().assign bit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.30 table().col().assign logical() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.31 table().col().assign string() . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9.32 table().col().assign arrdesc() . . . . . . . . . . . . . . . . . . . . . . . . . . .

9
233
233
234
235
236
237

13 APPENDIX1: Sample Programs238

14 APPENDIX2: SFITSIO built-in comment dictionary of FITS header

240

15 APPENDIX3: How to Use Handy TSTRING Class243

16 APPENDIX4: Convenient usage of DIGESTSTREAMIO class

245

10

SFITSIO User’s Reference Guide

1

Introduction

1.1

How long does it take to answer these questions using your favorite FITS
I/O library?

¨¥

Question 1
The FITS file called “foo.fits.gz” contains multiple binary table HDU. Write some code that
reads the file and set the variable called flag to 1 if the value of the first row of the column “X”
within the binary table “A” is not NULL and the value of the first row of the column “Y” within
the binary table “B” is larger than zero. Please take into account TZEROn and TNULLn, which are
set in the header. The various error checks and code fragment between #include and function§main can be omitted.
¦¨¥

Example solution to Question 1 using SFITSIO§¨

fitscc fits;
long row_idx = 0;
double v;
fits.read_stream("foo.fits.gz");/* Read the file */if ( isfinite(fits.table("A").col("X").dvalue(row_idx)) && /* Test the value */isfinite(v=fits.table("B").col("Y").dvalue(row_idx)) && 0 < v ) flag = 1;¦¥

Question 2
The file called “obj0.fits” contains observation data from four CCD chips. The resolutionof each CCD chip is 1024 by 2048, with the four of them stored as a single image of 4096
by 2048 resolution in the Primary HDU of obj0.fits. Read the FITS file and generate four
separate FITS files, with each having an HDU for the corresponding CCD chip. The names of
the generated files should be “CCD0”, “CCD1”, etc. Please take into account BZERO, which is
set in the header. Thet various error checks and code fragment between #include and function§main can be omitted.
¦¨¥

Example solution to Question 2 using SFITSIO§¨

const char *name[] = {"CCD0","CCD1","CCD2","CCD3"};
fitscc fits0, fits1;/* Original FITS and new FITS */fits0.read_stream("obj0.fits");/* Read observation frame */fits_image &pri0_img = fits0.image("Primary"); /* Define convenient alias */for ( i=0 ; i < 4 ; i++ ) {/* Append and copy HDUs */fits1.append_image(name[i],0, pri0_img.type(), 1024,2048);
pri0_img.copy(&(fits1.image(i)), 1024*i, 1024, 0, 2048);}
fits1.write_stream("obj0_separated.fits");/* Save as separate files */¦¥Question 3
The bias frame called “bias.fits.gz” and the flat frame “flat.fits.gz” are preprocessed.
There is also an unprocessed observation frame “obj1.fits”. Create a FITS using the observation frame that eliminates the upper and lower quarters after being processed using overscan(average value) and the bias subtracted and flat-field corrected. Information on the overscan
area is stored in the IRAF compatible format, as values for the BIASSEC keyword in the header.
Please take into account the observation frame being stored as 16-bit integer values and BZERO,
which is set in the header. The various error checks and code fragment between #include and§function main can be omitted.
¦

Ver. 1.2.1¨

11¥

Example solution to Question 3 using SFITSIO§

fitscc bias_fits, flat_fits, obj1_fits;
long y_len, sect[4];double v_stat[1];bias_fits.read_stream("bias.fits.gz");/* Read bias frame */flat_fits.read_stream("flat.fits.gz");/* Read flat frame */obj1_fits.read_stream("obj1.fits");/* Read raw object frame */fits_image &obj1pri = obj1_fits.image("Primary");/* Create alias */obj1pri.convert_type(FITS::DOUBLE_T);/* Convert data type */obj1pri.header("BIASSEC").get_section_info(sect,4); /* Get overscan info */obj1pri.stat_pixels(v_stat,1, "results=mean",/* Get mean value of */sect[0],sect[1],sect[2],sect[3]); /* Overscan section */obj1pri.subtract(v_stat[0]);/* Subtract overscan */obj1pri.subtract(bias_fits.image("Primary"));/* Subtract bias */obj1pri.divide(flat_fits.image("Primary"));/* Flat adjustment */y_len = obj1pri.row_length();/* Get height of image */obj1pri.data_array().crop(1,y_len/4,y_len/2);/* Rid top and bottom */obj1_fits.write_stream("obj1_done.fits");/* Save */¦Sample programs using SFITSIO are also shown in §13 APPENDIX1. They will be helpful tolearn SFITSIO programming.

1.2

Why is SFITSIO being developed?

Development of SFITSIO started as part of the data analysis project of ‘AKARI’, the infrared
astronomy satellite.
The project defined their standard data format to be ‘Time Series Data (TSD)’ (Figure1) for
their data analysis. TSD includes some binary table extensions in a FITS file, with the detector,

Figure 1: TSD, a standard data format used in software projects for “Akari”, the infrared astronomy satellite, can be opened using fv. All tables other than Primary are binary.

12

SFITSIO User’s Reference Guidesatellite, orbital information, etc. being stored in individual binary tables. That then means
all the data analysis tools for “Akari”, including those for entire sky surveys and various point
observations, should use the TSD as the first input file. The problem is, however, that TSD is avery complicated FITS file that is composed of many different types and structures of data and awide range of data storage methods, as shown in Figure 1. The decision was therefore made within
the project to develop a standard library that can access TSD more efficiently, and on the grounds
that it would be impractical for each analysis team to write their own code in order to access the
TSD.
The standard library developed in the project for the TSD (in C and IDL languages)1) loads
the entire FITS file into memory2) , basically with the API naturally representing the structure of
FITS 3) . As the result the following code can be used to access the TSD in the case of the C
language:¨§¥

tsd = fits_cache__open(class_level, NULL, "tsd_xxx.fits"); /* Read the file */(omitted: pieces of code used to set hdu_index and col_index)
ptr = tsd->btables[hdu_index]->columns[col_index].data; /* Access the column */¦The first line loads the FITS file into the memory and the line including “ptr = ...” gets the first
address of the column data within the table. Please note that the API represents the structure of
FITS in a natural manner, as the whole of FITS, the binary table HDUs, and columns are specified
in turn after tsd->. With an API of this level you can write code that accesses the various binary
table HDUs without very much effort, while still ensuring decent readability. The downside is,however, that this library is insecure because it always requires direct access to the memory, as
mentioned above, and lacks many of the features required of the generic FITS library, including
calculating TZEROn and TSCALn, which were not needed in the project.
SFITSIO is based on ideas found in the C library, and built from scratch using knowledge
lerned in its development. It has evolved into an even more sophisticated and more versatile FITS
library using C++’s “class”, which is upward compatible with struct, that has successfully resolved
all the problems found in the above-mentioned C library regarding the Binary Table HDUs, andwith support for image analysis via an intuitive API for Image HDUs. Refer back at the solution
for Question 1 in §1.1. It is immediately possible to write code that accessed the values in binary
tables using the names of the tables and columns and without any need for pointer variables.
Similarly, you can easily write clear code to do what you want, as revealed in Questions 2 and 3.
The policy used in the “Akari” project that conceals the FITS I/O as much as possible should
apply to any other project. There is an increasing need for versatile, performant, and high-level
FITS I/O libraries that can provide an easy way to accomplish different purposes according to theemergence of higher-performance equipment and larger-scale surveys.
SFITSIO was developed to provide useful solutions to this challenge. Additional solutions will
be provided in future versions in thereby keeping up with the development of the state-of-the-art
computing environments.

1)

The TSD-specific interface for IDL language, created by Dr. Hajime Baba, has a very logical design and elegant
coding, and which have a significant influence on SFITSIO.
2)
The rapid popularization of 64-bit Linux, which provides a lot of memory space, made it the perfect match formemory-mapped files.
3)
Strictly speaking “on-memory” is not essential feature with implementing “an API that represents the structureof FITS.” That said, however, on-memory is still a more realistic solution because disk-based implementation would
be too expensive.

Ver. 1.2.1

1.3

13

Why you should use SFITSIO to minimize any programming frustrations

1.3.1

SFITSIO does not force programmers to learn C++

Because SFITSIO is written in C++ your SFITSIO code gets compiled by a C++ compiler. You
may state: “No! I can’t use C++!!”. Relax. C++ is upwardly compatible with C so thatthe code can be written in C. That is, this code¨

#include <stdio.h>
int main(){
printf("Hello World\n");
}
§

¥

¦

can be compiled directly by the C++ compiler.
You don’t need to follow any such styles as (cout << "foo" << endl)4) shown in guidebooks
on C++. SFITSIO does not require that you follow the C++ style. You can therefore still write
the code using your C knowledge and style when you use SFITSIO.
1.3.2

You never have to worry about memory leaks with automated memory management

If you use the C language the memory space allocated using malloc() must be eventually freed
up using free(). If you ever forget to call free() a memory leak will occur. A small amount ofcode enables you to manage any possible memory leaks, but it can be a nightmare identifying any
memory leaks that occur in large amounts of code. In that sense, it is just like containment of
nuclear fuel in a fission reactor. It is very difficult to correct any memory leaks if you do not havestringent coding rules in place.
In order to minimize the chance of any such problems occurring, SFITSIO automates any
memory management related to FITS by taking advantage of C++ “classes.”This basically saves programmers from needing to call malloc() and free(), and therefore
from memory leaks occurring in FITS manipulations5) . For example, reading a FITS file withSFITSIO involves the following steps:(1) You instruct SFITSIO to read the FITS file (in this example, myimage.fits.gz) using itsAPI.
¨fits.read_stream("myimage.fits.gz");§¥¦(2) SFITSIO will analyze the FITS file and allocate the required memory space.
(3) SFITSIO will copy all (or part of) the content of the FITS file into the allocated memory.
(4) You can access the data you want (in this example, CRVAL1 in the header) in the memory
using the SFITSIO API.
¨

printf("crval1 = %f\n", fits.image("Primary").header("CRVAL1").dvalue());§(5) The allocated memory space will be automatically freed up as soon as it falls out of scope.
You only need to write code for (1) and (4) and not worry about any memory leaks.
Leave the memory management to the library and never have to struggle with memory leaks!
4)
5)

The Google C++ Style Guide recommends that programmers use printf() instead of the cout << ....
The use of new could lead to a memory leak, but is barely required.

¥
¦

14

SFITSIO User’s Reference Guide

1.3.3

The API naturally represents the structure of FITS—you will never forget it
once you have used it!

The reason why you will never forget SFITSIO’s API once you have used it lies in the structure of
the API.
So, what does SFITSIO’s API look like? Let me explain using the following three examples.
(1) To read and print the value of CRVAL1 in the header of the Primary HDU:¨

printf("crval1 = %f\n", fits.image("Primary").header("CRVAL1").dvalue());§¥¦(2) To read and print the pixel value of the coordinates (x, y) of the image in the Primary HDU:¨¥

printf("pixel = %f\n", fits.image("Primary").dvalue(x,y));§¦(3) To read and print the value of the column “RA” in the first row of the binary table HDU
called“CATALOG”:¨¥
printf("ra = %f\n", fits.table("CATALOG").col("RA").dvalue(0));§¦

Have you got a feel for how it can be used now?
Yes, that’s right. The API naturally represents the structure of FITS. For example, in the third
example you can read:
FITS that has a table that has a column that has a double value
If you replace “that has a” with “.” and place the functions in the same order as FITS is structured
you can then use the API. Moreover, SFITSIO has a very limited number of functions that need
to be memorized.
There are only five functions that are essential as structural members:hdu()
Any HDU

image()
Image HDU

header()
FITS header

table()ASCII/Binary Table HDU

col()column in table

In addition, all you have to do is memorize the function names to read the values: dvalue(),lvalue(), llvalue(), svalue() (which return double, long, long long, and string respectively)
and assign(), a function to write values, in order to be able to do all the basic read and write
operations of FITS.
Please note that dvalue() and similar functions would return a value appropriately converted
from whatever was in the FITS file, were it a string or an integer. Conversely, assign() would
convert the value into what is appropriate for storage in FITS, depending on the type of theargument6) . Moreover, these functions are capable of converting values based on keywords BZERO,BSCALE, TZEROn, and TSCALn in the header, which are cached on the library side, thus saving us
from writing code to parse the header. Of course you can read/write unsigned integer values simply
with lvalue()/assign() and setting BZERO or TZEROn appropriately.
1.3.4

Easy random access across multiple HDUs

SFITSIO makes heavy use of memory mapped files and thus saves programmers from having toseek within files and deal with memory management. As mentioned in §1.3.3 its API takes thesame form as the structure of FITS, thus immediately enabling you to write code for random accessacross multiple HDUs, and as revealed by the solution to §1.1.
6)

C++ enables you to declare multiple functions with the same function name but with different argument(s).

Ver. 1.2.1
1.3.5

15

“High-level API” for type conversion and processing on ZERO, SCALE, andNULL

SFITSIO provides a “high level API” that includes functions mentioned in §1.3.4 such as dvalue()and assign(), which programmers typically use.
These high-level API functions convert types, ZERO and SCALE keywords, as well as BLANK
and NULL values. Although great care has been taken in implementing these functions in SFITSIO
in order not to degrade the performance, the overhead of function calls can accumulate in the caseof small amounts of operations per pixel performed with a large number of pixels. In that case you
can use the low-level API and image-processing API, which will be explained shortly.
1.3.6”Low and ultra-low level” API for faster operation

If you are not comfortable with the performance of the high-level API you can use the “low level
API” without processing ZERO, SCALE, or NULL, or even the “ultra-low level API” which canaccess the addresses of internal memory buffers managed by SFITSIO.
You can thus creatively use the high level API and the low level API in more cost-effective
software development.
1.3.7

Image-processing API

Recently, analysis of large-sized FITS images is quite common. SFITSIO provides a high-performance
image-processing API that enables a small amount of code to perform area scanning, copy andpaste, the four basic arithmetic operations with images and scalar values, and image scanning andoperations with user-defined functions.
1.3.8

Functions support variable-length arguments in a printf()-compatible manner

The specification of a format string plus variable-length arguments is one of the most powerful anduseful features in LIBC string operations. SFITSIO provides a wide range of functions with thesuffix “f”, such as colf() andheaderf(), which can take arguments fully compatible with printf()
function. You can creatively use them to reduce your coding efforts. For example, you can use
headerf() to write code:¨¥fits.image("Primary").headerf("CRVAL%d",i).dvalue()§¦

where i is a variable of the int type.
1.3.9

Transparent handling of compressed files and files on Web/ftp servers

SFITSIO automatically compresses/expands files in the gzip or bzip2 formats on local storage or
Web/FTP servers, and without requiring the use of any special API.
Whereas the gzip format is supported in other FITS I/O libraries as a matter of course, SFITSIO can handle any compression format by simply installing the corresponding command, forexample fpack.
1.3.10Comment dictionary for the FITS header and FITS template function

SFITSIO has a comment dictionary for keywords defined using the WCS and FITS conventions
and those commonly used. It saves programmers from writing comments for each keyword in the
FITS header. For example:

16

SFITSIO User’s Reference Guide¨¥

fits.image("Primary").header_fill_blank_comments();§¦

This instantly fills all uncommented header records in the Primary HDU with the corresponding
comments from the dictionary.
In addition, SFITSIO supports template files (§8) in the same manner as CFITSIO. A template
file is a text file that can be used to define the content of FITS with somewhat lenient syntax like
FITS headers, which can be used to create a new FITS file (object) without any data. This
enables you to easily develop generic tools. Also in the case of FITS created from templates any
uncommented portions of the template will automatically be populated with comments, thereby
enabling template users to write just the bare minimum.
Needless to say, if programmers do find the content of the available dictionaly in SFITSIO to
be unsatisfactory they can append/modify its content.

1.3.11Super-convenient s++ script

In order to make executable files from source code with SFITSIO you will need to link it with afew standard libraries. The accompanying s++ script will take care of that and you simply issue
the command:¨¥$ s++ my_program.cc -lsfitsio§¦

to finish compiling it. It can also create a source template file containing #include directives andthe main function for you if the source file specified in the argument does not exist, thus effectively
saving you from having to write the same portion of code for different projects. SFITSIO is very
convenient for casual use thanks to its s++ script.

1.3.12

CFITSIO-like, disk-based FITS I/O is also supported

It might not be a good idea to load the entire FITS file into memory if you want, for example:• to quickly scan the header only, thus minimizing memory usage, or• to calculate the median of a number of image files.

SFITSIO provides an API to use to load a single Header Unit into memory or to skip reading
one Data Unit. In order to use this API the programmer starts off by declaring the stream handler
with which the FITS file is opened. Next, the stream handler is given to the target member
function in order for SFITSIO to scan the necessary amount of FITS files. For example, if you
use one of the member functions to load the header the stream is placed at the start point of theconsecutive Data Unit. In this case, header-related high level API functions are still available andsomething like disk-based image access would be a relatively simple task. Of course, you can alsoelaborate on disk access as much as you want in the case of a seekable stream.

Ver. 1.2.1

17babababababababababababababababababababab
SFITSIO’s memory managements close to scripting languages
Assigns string "ABC" to $A

Assigns all information(header, image, etc.)$A = "ABC";

fits.read_stream("foo.fits");

There is an internal
string buffer managed
automatically

There are internal buffers to store header and image.
Internal buffers are automatically managed.

printf("%s\n",$A);
Returns addressof bufferperl

Gets length of HDUs.

printf("%ld\n",fits.length());
value of long type

SFITSIO

The basic idea of SFITSIO is that the whole FITS file can be treated as strings in scripting
languages (e.g. perl). According to that idea we developed SFITSIO in order to minimize
the programmers’ load with the I/O of FITS as much as possible. Substitution of strings
into variables written in scripting languages is frequently used. In fact, the script engine
calculates, allocates, and manages the memory space behind it. However, these are notvisible to the programmers.
On the other hand, and in the case of the conventional and procedural-type FITSI/O libraries including CFITSIO, we have dealt with the bothersome tasks of calculating
memory space for the header strings for data areas, allocating the area using functions
such as malloc(), and freeing up any unnecessary space using free().
Please think about this a little bit. If implementation of variables in scripting languages
applies to the I/O of FITS it would be basically impossible for it to cause the same botheras with using the conventional FITS-I/O, wouldn’t it?
Now, “Class” in the C++ language. If we use “Class” smartly it is possible to box in
the whole FITS file into one variable (called an object because of its size). Figure compares
the case of perl with that of SFITSIO. In the case of perl the string "ABC" is substituted
as a variable while the whole FITS file "foo.fits" is substituted for by another variable(object) named “fits” in SFITSIO. In both the cases of perl and SFITSIO the necessary
memory space gets automatically be allocated and managed. The FITS files include
several types of information on the headers and image data so that the getting/putting of
the information from/into the variables (objects) need to use functions (so called member
functions). Although the variables have to be more manually manipulated than with script
languages it is clear that FITS files can be treated in an analogous manner to variables inperl.
In this way using the idea of classes in C++ frees programmers from the bother ofmemory management, and provides intelligible APIs that reduce the load on programmers
as much as possible.

1.4

FAQ

• What about support for users?
SFITSIO and SLLIB is “officially supported software” of the ISAS/JAXA Data Utilization

18

SFITSIO User’s Reference Guide
Group and was jointly developed and maintained by the Data Utilization Group and myself(Yamauchi). Formally, however, it is open source software provided under the MIT licenseand has no warranty whatsoever.
• Has it been used in any actual projects?
It has been used internally by JAXA to my knowledge. More specifically, it has been usedin archive development projects across almost all areas, including the entire sky mapping
project, FITS-related tool development in infrared and moon/planetary science areas, andthe L1TSD project for ASTRO-H.
• It is a C++ library for use by experts only, isn’t it?
Definitely not! On the contrary it is more useful for beginners as they can easily perform
traditionally difficult operations.
SFITSIO incorporates carefully selected truly useful C++ features rather than C++-proprietaryfeatures that can confuse users from the astronomy industry with average skills. In addition,
this manual was written for those who have experience with the C language only. Experience
with C++ is, therefore, not required to use SFITSIO.
• How fast is it?
It depends on the API used: a high level API, low level API, or ultra-low level API. The
former requires less development efforts at the cost of slower operations, whereas the latter involves more development efforts but which operates faster. There is also an image-processing
API, which enables you to develop faster applications with less effort if the API fits the
purpose.
Basically, functions that return sizes such as the number of pixels and the ultra-low level
API functions are inline member functions. They have a minimum overhead with function
calls. Inline member functions will be even more widely used in future versions of SFITSIO.
R
By the way, SFITSIO can be compiled using the Intel°
C++ Compiler.

• Can I use 16-bit unsigned integers?
Yes. The high level API and image-processing API supports BZERO conversions. In the caseof these APIs no value conversions have to be dealt with by the programmers. To save a
16-bit unsigned integer into a new FITS all you have to do is set BZERO to 32768 (refer to§5.9).
If you are uncomfortable with the high-level API for performance reasons you may find theconvert type() member function (refer to §12.6.13 and §12.8.28) more user friendly when usedin combination with the ultra-low level API. Please refer to the code example in §5.11.

Ver. 1.2.1

2

Installation and Getting Started with SFITSIO

2.1

Supported OS

19

SFITSIO supports both 32 and 64 bit version of Linux, FreeBSD, MacOSX, Solaris, and Cygwin.
SFITSIO requires GCC g++ version 3 later (the author has verified operations on g++ 3.3.2
or later.)

2.2

Building and installing SFITSIO

To build SFITSIO you will need SLLIB (Script-Like C-language library) version 1.2.1 or later. Install the libraries of zlib, bzlib, and readline (probably named zlib-devel, bzip2-devel, and readlinedevel as RPM)7) that are required by SLLIB.
If you haven’t installed SLLIB yet install it in the order below. Expand the archive file of
SLLIB and run make.8)¨¥$ gzip -dc sllib-x.xx.tar.gz | tar xvf $ cd sllib-x.xx$ make§¦Compilation of the 32 or 64-bit versions is possible by adding options to the compiler, forexample:¨¥$ make CCFLAGS="-m64"§¦

If you use 32-bit OS, gcc might not turn SSE2 on by default9) . You can append options for
SSE2 to improve performance as follows:¨¥$ make CCFLAGS="-msse2 -mfpmath=sse"§¨

Install SLLIB.

$ su§# make install32¦¥¦

With the 64-bit OS run make install64 instead. The default installation directory of libsllib.a
is /usr/local/lib and /usr/local/lib64 (or /usr/local/lib/64 with Solaris) in the case of
install32 and install64, respectively. At the same time all header files are copied to/usr/local/include/sli and the wrapper script of g++, named s++ is installed to /usr/local/bin.
Next, install SFITSIO in the same way. Expand the archive file of SFITSIO and run make.10)¨¥$ gzip -dc sfitsio-x.xx.tar.gz | tar xvf $ cd sfitsio-x.xx$ make§¦Analogous to the compilation of SLLIB, you can append options to the compiler, e.g.
¨$ make CCFLAGS="-m64"§¨$ make CCFLAGS="-msse2 -mfpmath=sse"

§

¥
¦
¥
¦

If any errors get reported on running make, specify the directory to which the header files of
SLLIB were installed for INCDIR in Makefile.
Install SFITSIO.
7)

With Debian they will be zlib1g-dev, libbz2-dev, and libreadline5-dev.
Shared library can be made by make shared by advance users.
9)
It is enabled by default on 64-bit OS.
10)
Shared library can be made by make shared by advance users.
8)

20

SFITSIO User’s Reference Guide

¨

¥

$ su
§# make install32¦

With the 64-bit OS run make install64 instead. The default installation directory of libsfitsio.a
is /usr/local/lib and /usr/local/lib64 (or /usr/local/lib/64 with Solaris) in the case of
install32 and install64, respectively. At the same time, all the header files are copied to/usr/local/include/sli.
That’s all the installation takes.

2.3

Installing multi-threaded compression utilities (optional)

SFITSIO-1.2.0 (or later) automatically detects “pigz” (http://zlib.net/pigz/) and “lbzip2”(http://lacos.hu/) installed in your environment, and performs multi-threaded compression anddecompression when writing and reading local files of the gzip or bzip2 formats. A multi-core CPU
improves the performance of compression and decompression (performance of compression
gets drastically accelerated). Install11) pigz or lbzip2 if you want to enable this feature.

2.4

Operational checks using sample programs

The following code is an SFITSIO version of the ‘Example Program’ found in the second chapterof the user’s guide of CFITSIO 12) .
¨#include <stdio.h>#include <sli/fitscc.h>using namespace sli;¥/* required by every source that uses SFITSIO */int main( int argc, char *argv[] ){fitscc fits;/* fitscc object that expresses a FITS file */const long width = 300, height = 300;/* size of image */long len_written, i, j;/* Create the Primary HDU */fits.append_image("Primary",0, FITS::SHORT_T, width,height);
fits_image &pri = fits.image("Primary");/* Add an "EXPOSURE" header record */pri.header("EXPOSURE").assign(1500.).assign_comment("Total Exposure Time");/* Set the values in the image with a linear ramp function */for ( j=0 ; j < height ; j++ ) {for ( i=0 ; i < width ; i++ ) pri.assign(i + j, i,j);}/* Output a FITS file */len_written = fits.write_stream("testfile.fits");
printf("saved %ld bytes.\n", len_written);return (len_written < 0 ? -1 : 0);}§¦Now, compile it with the s++ command.
11)
12)This can be done before or after the SFITSIO installation.
You may notice the code is more readable than the CFITSIO sample code.

Ver. 1.2.1¨

21¥$ s++ fitsout.cc -lsfitsio
g++ -I/usr/local/include -L/usr/local/lib -Wall -O fitsout.cc -o fitsout -lsfits
io -lsllib -lz -lbz2 -lreadline -lcurses$ ./fitsout
§
¦

2.5

Getting started with SFITSIO• For those who are in a hurry or just want to experiment:
Proceed to §5 ‘Tutorial’ after browsing §4.7 ‘Member functions classified by purpose and API
level’.
• For FITS experts:
Proceed to §4 ‘Representation of FITS data structures and APIs with SFITSIO’s class structure’• For those who have little knowledge of FITS and want to use this opportunity to learn it:
Carefully read §3 ‘Review of FITS data structures’ and proceed to §4 and §5.

22

SFITSIO User’s Reference Guide

3

Review of FITS data structures

3.1

Overall structure
FITS File

FITS Header
SIMPLEBITPIX
NAXIS

=
=
=

EXTEND

=

:
:
:
:

T
16
2
T

XTENSION= ’IMAGE’
BITPIX =
16
NAXIS
=
2
:
:

XTENSION= ’BINTABLE’
BITPIX =
8
NAXIS
=
2
:
:

Header Unit
Header Data Unit (HDU)
Data Unit
Header Unit
Header Data Unit (HDU)
Data Unit
Header Unit
Header Data Unit (HDU)
Data Unit
Figure 2: Overall structure of FITS file

The overall structure of a FITS file is a combination of multiple “HDUs (Header Data Units)”,
that are comprised of a pair of “Header Unit” and “Data Unit”, as shown in Figure2. The Data Unit
is comprised of ASCII or binary data such as an image or a table, while the Header Unit contains
various information on the data and specifications of the Data Unit stored as a set of “keyword =value” records in the plain text format of 80 characters and without linefeed characters. The byte
length of each Header Unit or Data Unit needs to be equivalent of the integral multiple of 2880.
The blank space at the end of each Unit arising from the convention used is usually padded withblank spaces (0x20) in the case of a Header Unit, or a NUL character (0x00) in the case of a Data
Unit13) .
The three HDU formats that fulfill the FITS convention are: “Image”(§3.3), “ASCII Table”(§3.4), and “Binary Table”(§3.5). The first HDU in a FITS file is called the “Primary HDU”,
and which for historic reasons should be an Image format. The number of HDUs can be identified
as one if the EXTEND keyword has a value of F, but the entire FITS file need to be parsed todetermine the number of HDUs if EXTEND equals T.
The binary data in Data Units are stored in the big-endian format with both integer andfloating-point (IEEE 754) values. Please note that no data alignment can be specified and in somecases you will have no proper memory access even if you have copied the entire content of the Data
Unit into memory and converted the different types of endian orders, although that does dependon your HDU and data processing system.

3.2

Header Unit

The content of Header Units of a FITS file, which will be shown in the sections starting from §3.3
in more detail, is somewhat old-fashioned: a sequence of records in a format ”keyword = value/ comment” starts from the beginning, ends with the END keyword, but lacks the mechanism to
13)

A significant number of FITS with EXTEND being F that are not padded in integral multiples of 2880 bytes.
SFITSIO does not treat this as an error, although the author is not sure whether this is a valid convention or not.

Ver. 1.2.1

23

differentiate between the value types as the INI file in Windows does. A record consists of printable
80 characters and can be of either of four different record formats:(1) format in “keyword = value / comment”,(2) format in “keywordt arbitrary string”,(3) format in “tttttttt arbitrary string”, or(4) the “END” keyword.
It is recommended that the reading or writing of FITS file should not modify the order of theserecords, although there is no guarantee that the order will be preserved. The keyword is limited
to a length of eight characters and can only be composed of capital letters, digits, “-”, and “_”.
The letter in the ninth position is = in the case of (1) and a blank space in the case of (2).
There is no convention of an alphanumeric character being in the ninth position14) . The value iseither an integer, a real number, a logical value (T or F), or a string, and should be quoted only if
it is a string. Characters after / can be omitted.
In the case of (2) the FITS convention only allows for “COMMENT and “HISTORY”, but in practicenon-conventional keywords such as “CONTINUE” and “HIERARCH” are also commonly used. You
therefore cannot determine whether the format is (1) or (2) based on only the keywords.
The current FITS convention does not specify how very long string values should be stored,
although the convention of the CONTINUE keyword is commonly used (refer to §9.1).

3.3

Image HDU

Image HDU is a simple array of n-dimensional image data that is packed into a Data Unit. The
supported types of data are: 8-bit unsigned integers, 16-bit, 32-bit, and 64-bit signed integers, and32-bit and 64-bit floating point numbers. However, multiple data types cannot coexist within asingle Data Unit15) .
It can be placed either in the Primary HDU or in and after the second HDU; the first part of
the FITS header differs in these cases, as show below:¨¥

SIMPLEBITPIXNAXISNAXIS1NAXIS2EXTEND

§
¨

=
=
=
=
=
=

XTENSION= ’IMAGE
BITPIX =NAXIS=NAXIS1 =NAXIS2 =PCOUNT =GCOUNT =§T / conformity to FITS standard
32 / number of bits per data pixel
2 / number of data axes
1024 / length of data axis 11024 / length of data axis 2
T / possibility of presence of extensions’/ type of extension
32 / number of bits per data pixel
2 / number of data axes
1024 / length of data axis 11024 / length of data axis 2
0 / number of parameters per group
1 / number of groups¦¥¦

In and after the second HDU the XTENSION must be placed at the beginning of the header, whichthen determines the HDU type.
Different data types are specified by BITPIX (the number of bits), with negative BITPIX meaning
the floating point type. The size of the data array is specified by NAXISn and the data can have
14)This provides for the possibility of keywords being used of nine characters or more, while still ensuring compatibility with traditional data.
15)
This then means that copying an entire Data Unit to an area allocated by malloc() and then converting between
the different endian orders will result in memory access without any alignment problems.

24

SFITSIO User’s Reference Guide

an arbitrary number of dimensions. 2D data is most commonly used, but occasionally 3D or 4D.
In the case of 3D data they may represent the R, G, and B components in that order. This is
not specified in the FITS conventions but is commonly called the “RGB Fits Cube” and can behandled as RGB data using ds9 etc.
The physical value of the pixel to be read can be determined using BZERO and BSCALE values
in the header:
Physical Value = BZERO value + value of pixel × BSCALE value
where BZERO and BSCALE will be 0.0 and 1.0, respectively, if they do not exist. BZERO being set to32768 enables 16-bit unsigned integers to be conveniently stored in a Data Unit using BITPIX=16.
In the case of integral data types the value for data array elements to be considered undefined
pixels16) can be determined using BLANK in the header. NaN is treated as a value for undefined
pixels in the case of floating point data types.
Although there is no FITS convention for the origin and the axes when 2D image data is plotted
it is naturally considered that the origin will be at the lower left corner and the axis for the first
dimension oriented right and the axis for the second vertically.
With regard to WCS the projection method and reference points, etc. can be recorded in
the header using keywords such as CTYPEn, CRPIXn and CRVALn. Because the FITS conventions
specify very basic keywords those proposed by the so-called WCS Paper series are considered defacto standards17) for the WCS conventions, and which cover a wider range of keywords. Pleaserefer to the original documentation and the FITS guide issued by the National Astronomical
Observatory of Japan.
If you do use WCS it should be noted that there is no conventional agreement as to the following:• whether the pixel coordinate of the origin at the lower-left corner is one or zero, and• whether the integral value of the pixel coordinate refers to the center or the left edge of the
pixel.
Generally with FITS the pixel coordinate of the origin at the lower-left corner is one, and theintegral value of the pixel coordinate refers to the center of the pixel. Ds9 and fv also follow these
agreements, so there is really no advantage in using any different definitions. However, please
do note that the author of a particular FITS file may have different ideas with regard to thesedefinitions.

3.4

ASCII Table HDU

The ASCII Table HDU for a single table simply consists of printable characters. The content of
the table is stored in the Data Unit. The byte data of the Data Unit is packed from the firstcolumn in the first row without any empty spaces on a “line-by-line” basis, which means the byte
data starts in the first column of the first row of the table, followed by the second column of thefirst row, the third column, and so on and without any empty spaces.
The content of the Header Unit consists of the required keywords for the 2D data with BITPIX=8
in the Image HDU plus keywords that describe the table. This means the Data Unit can simply
be skipped without needing to be aware of any ASCII Table HDU. Just like the Binary TableHDU the ASCII Table HDU cannot be the Primary HDU. The header always therefore starts withXTENSION, as shown below:
16)

The raw value of any data array elements, without taking BZERO or BSCALE into account.
There are also other totally different conventions to the WCS Paper series, for example the DSS FITS. These
special WCS conventions can be used with popular available software, including WCSTools.
17)Ver. 1.2.1

25

¨

¥

XTENSION= ’TABLE’
BITPIX =NAXIS=NAXIS1 =NAXIS2 =PCOUNT =GCOUNT =TFIELDS =TTYPE1 = ’Freq’
TBCOL1 =TFORM1 = ’I10’
TTYPE2 = ’L10Pointer’
TBCOL2 =TFORM2 = ’I10’
EXTNAME = ’HTMLevel10Idx’§END/ type of extension
8 / number of bits per data element
2 / number of data axes
21 / width of table in bytes
256 / number of rows in table
0 / number of parameters per group
1 / number of groups
2 / number of fields in each row/ field name
1 / starting position in bytes/ display format/ field name12 / starting position in bytes/ display format/ name of this HDU¦

The keywords from XTENSION to TFIELDS are arranged in a predefined order, of which BITPIX,
PCOUNT, and GCOUNT have the fixed values 8, 0, 1, respectively.
Header keywords in an ASCII Table have meanings shown below. By the way, the column
in a table is called a “field” with FITS, although the term “column” is used here for the sake ofconsistency.
keyword
NAXIS1NAXIS2TFIELDSTTYPEnTUNITn
TFORMnTBCOLnTZEROnTSCALnTNULLnmeaning
the width (number of bytes) of the table
the height (number of bytes) of the table
the number of columns in the table
the name of the table column n
the physical unit of the value of the table column n
the data format for the table column n in the ANSI FORTRAN-77 format:(“Aw”) for a string, (“Iw”) for a decimal integer, or (“Fw.d”, “Ew.d”, or “Dw.d”)
for a real number
the byte-wise start point (1-indexed) for the column n in a specific row of thetable
the zero point applicable to the table column n
the scaling factor applicable to the table column n
the string to be used for any undefined values in the table column n

Where TZEROn and TSCALn fulfill the same role as BZERO and BSCALE in the Image HDU, althoughrarely used.
The ASCII Table HDU has a simple structure and can be created relatively easy with low level
FITS libraries. However, that said, shortcomings of the ASCII Table include that it is impossible
to extract the data width of a column from a single header record, and therefore it does not work
well with FITS templates (§8).

3.5

Binary Table HDU

The format of the Binary Table HDU can be considered to be a binary version of the aforementioned
ASCII Table HDU, however, with more data types and various extension features, thus making it
rather a complex and not very suitable for the word “SIMPLE” to be used with it. It has as justmuch flexibility as complexity, however, being able to meet very high-level requirements such as
storing complex and mysterious telemetry data from astronimy satellites.
One of the biggest differences between the Binary Table HDU and the Image HDU or the
ASCII Table HDU is the existence of a Reserved Area and Heap Area in addition to the Data

26

SFITSIO User’s Reference Guide

Binary Table HDU

FITS Header

Header UnitXTENSION= ’BINTABLE’
BITPIX =
8
NAXIS
=
2
:
:
NAXIS1NAXIS2

Data Array

THEAP

Reserved Area
PCOUNT

Data Unit

Heap Area

Figure 3: The structure of the Binary Table HDU. The size of each Data Unit can be determinedfrom the values of NAXIS1, NAXIS2, PCOUNT, and THEAP. If there is no Reserved Area NAXIS1 ×
NAXIS2 will equal to THEAP and PCOUNT the size of the Heap Area.
Array, as shown in Figure 3. A table is stored in the Data Array on a “line-by-line” basis in
the same manner as the ASCII Table HDU, and packed with binary data without any empty
spaces. The Reserved Area appears to have been made available for disk-based FITS applications
and no data can be stored in this area18) . The Heap Area is where real data for a so-called“variable length array” is stored. To skip over the Data Unit you should take into account the factthat the Data Unit is padded in integral multiples of 2880 bytes, as well as the data length, i.e.
NAXIS1 × NAXIS2 + PCOUNT.
Here is an example header:¨¥

XTENSION= ’BINTABLE’/ type of extension
BITPIX =8 / number of bits per data element
NAXIS=
2 / number of data axes
NAXIS1 =22 / width of table in bytes
NAXIS2 =4096 / number of rows in table
PCOUNT =12897220 / length of reserved area and heap
GCOUNT =1 / number of groups
TFIELDS =6 / number of fields in each row
TTYPE1 = ’ENERG_LO’/ field name
TFORM1 = ’E’
/ data format : 4-byte REALTUNIT1 = ’keV’
/ physical unit
(omitted)
TTYPE5 = ’N_CHAN ’/ field name
TFORM5 = ’1I’/ data format : 2-byte INTEGERTTYPE6 = ’MATRIX ’/ field name
TFORM6 = ’1PE(3353)’/ data format : variable length of 4-byte REAL
EXTNAME=’MATRIX’/ name of this HDU§¦

Just like the ASCII Table HDU the Binary Table HDU cannot be the Primary HDU, the header
always starts with XTENSION, and the keywords up to TFIELDS are in a predefined order. The
keywords BITPIX and GCOUNT have the fixed values 8 and 1, respectively. In this example you can
see there is a Heap Area but no Reserved Area from the fact that PCOUNT is non-zero and THEAP
is not defined.
Header keywords found in the Binary Table HDU and their meaning are shown below. I will
point out some of the idiosyncrasies when compared to run-of-the-mill tables.
18)

The author has never seen a FITS file that had a Reserved Area.

Ver. 1.2.1
keyword
NAXIS1NAXIS2TFIELDSTTYPEnTUNITnTDISPn

TFORMnTDIMn

TNULLnTZEROnTSCALn27
meaning
the width (number of bytes) of the table
the height (number of bytes) of the table
the number of columns in the table
the name of the table column n
the physical unit of the value of the table column n
the display format of the table column n in the FORTRAN-77 format: (“Aw”)
for a string, (“Lw”) for a logical value, (“Iw”) for a decimal integer, (“Fw.d”,“Ew.d”, “Gw.d”, or “Dw.d”) for a real number, (“Bw”) for a binary integer, (“Ow”)
for an octal integer, or (“Zw”) for a hexadecimal integer
the data type for the table column n;value of TFORMn typebyte length of the column
rL
logical value (’F’ or ’T’)
1×r
rX
bit
b(r − 1)/8c + 1
rB
8-bit unsigned integer
1×r
rI
16-bit signed integer
2×r
rJ
32-bit signed integer
4×r
rK
64-bit signed integer
8×r
rAa
character (string)rrE
single-precision floating number
4×r
rD
double-precision floating number
8×r
rC
single-precision complex number
4×2×r
rM
double precision complex number
8×2×r
rPt(emax )32-bit array descriptor (array length, heap offset) 4 × 2 × r
rQt(emax )64-bit array descriptor (array length, heap offset) 8 × 2 × r
r is the number of cells that can be omitted if it is one. a is the length of thestring per element when defining a string array (refer to §9.2). t is the typeused when the Heap Area is being referred to. emax is the maximum number ofreferences to the Heap Area per row.
the definition of a multi-dimensional array in the table column n, which differsfrom r in TFORMn in that it does not affect the byte length of the column but
is used in interpreting the data. It can be specified in the case of r being morethan 1 with the form of (l,m).
the value to be used for any undefined values in the table column n
the zero point applicable to the table column n
the scaling factor applicable to the table column nWith Binary Table HDUs understanding the data types using TFORMn is the most important.
The most important feature with this data type definition is the fact that with a single column canhave multiple cells, which is called a fixed-length array in the case of r more than 1 in the value of
TFORMn. For example, TFORM99 = ’48I’ defines 48 16-bit integers in a single column. This may
be slightly counterintuitive, but it helps to think about the table having some depth and 48 cells
being lined along the depth-ward axis. In addition, if you define TDIM99 = ’(8,6)’, the 48 cells
are interpreted to be a 8 × 6 two-dimensional array, and which is called a multi-dimensional array.
Probably the hardest part about understanding data type definitions is the so-called “variablelength array”, which is the case where TFORMn is rPt or rQt19) . In this case it helps to think about
cells being in line with the depth-ward axis and the number not being fixed, however the data will
19)

If r were more than 1 in rPt or rQt, that would result in multiple variable-length arrays in a single column;
although I myself have never seen any such FITS file with that definition. Most tools do not support any suchdefinitions either.

28

SFITSIO User’s Reference Guide

be stored in a very special manner. In the case of a variable-length array the real data of the array
will be stored somewhere in the Heap Area, and the “index to the Heap Area (offset)” and the“array length” of the row stored in the cell of the table itself (the data array in the Data Unit). A
few pages prior we came across the definition TFORM6 = ’1PE(3353)’ in an example of a header,
and which means the maximum number of the elements of the array is 3353 and that 32-bit floating
point numbers (with the symbol “E”) are stored somewhere in the Heap Area. For example, if thepair of numbers (12, 34) that are the array descriptor, are stored in a certain row of the column
concerned in the table itself it means that 12 32-bit floating point numbers get stored starting fromthe 34 byte offset from the beginning of the Heap Area. It should be noted that multiple arraydescriptors may reference the same address in the Heap Area, regardless of the columns or rows in
the main table20) . In other words, this means you cannot convert between different endian orders
unconditionally in any Heap Area copied into memory. There are no alignment conventions either,of course, and care should be taken in reading or writing to the memory. Moreover, when defining
any high-level API in the FITS library references to the Heap Area should be normalized in someway for the sake of automated processing.
Definition of the NULL value is the value assigned to TNULLn in the header for integral types,
NaN for real number types, and the character code 0 in the case of the logical type. The NULL
value for the string type should be determined by the author.
At least conventionally more detailed format descriptors can be used for TDISPn than thosedescribed in the table above, but few tools or libraries support all of them.
TZEROn and TSCALn plays the same role as BZERO and BSCALE in the Image HDU. They arecommonly used to store unsigned integers, as with images.
Keywords used in the Binary Table HDU are often extended locally to represent column information. Well-known ones include TLMINn, TLMAXn, TDMINn, and TDMAXn; SFITSIO also supports
TALASn (alias definition for a column) and TELEMn (definition of element name in a fixed-length
array), and which were proposed during the “Akari” project of ISAS/JAXA (§10.8, §10.9). But
any such locally extended keywords will have the problem of where deleting or moving a column
will not result in the expected header because some libraries cannot determine whether they concern column information or not. Unfortunately, there is no agreement with the FITS standards inthis regard. SFITSIO proposes a solution for this problem by listing locally extended keywords asvalues of TXFLDKWD, and which was devised during the L1TSD project of ISAS/JAXA (§10.7).

20)This would have some advantages in the case of any repetition of the same data sequence, although it would
be too difficult to implement with memory-mapped or disk-based systems.

Ver. 1.2.1

4

29

Representation of FITS data structure using SFITSIO classstructure and API

We have now reviewed the FITS structure in some detail via §3. The reason why this manualcontains these explanations of FITS is the fact that “the API of SFITSIO naturally represents the
structure of FITS”, as mentioned in §1.3.3.
¿From the perspective of developers, designing any such API is basically the same as designingclass structures. An important task in any such design is to find a way to naturally “copy” thetarget structure (in this case, FITS) to the class structure. Conversely, it is important that usersof the library recognize the way the structure is “copied” in order to understand the API.
In this section we will cursorily review the way the FITS structure is “copied” to C++ theclass structure, as well as the corresponding API. Although this manual can be used without thatknowledge, I believe that you can learn the API easier if you do possess knowledge on it, at least
to some extent.

4.1

Overview of class structure and access to HDU via API

fits.image("Primary"). ...
fitscc class
User’s Object
fits_image classinherited

fits_hdu classfits.hdu(0L). ...

fits_header
class
FITS Header

Imaging Data

fits_table classinherited

fits_hdu classfits_header
class

Table Data

FITS Header

fits.table(1L). ...
Figure 4: Overall internal structure of the object of “fitscc” class, which corresponds to one FITS
file (right) and API that accesses each HDU (left). In this example one FITS file contains one
Image HDU and one Binary Table HDU.
With SFITSIO the content of FITS is loaded into the memory buffer in any case of a FITS
file being read or a new FITS created. The memory buffer is managed by a top-level fitscc classobject. Figure 4 provides an example of where a fitscc class object has the content of one FITS
file. If you compare it with Figure 2 and Figure 3, which illustrate the FITS structure, you will
notice the FITS data structure gets “naturally copied” into the object.

30

SFITSIO User’s Reference Guide

A FITS file is represented by the fitscc class and an HDU in general by a fits hdu class, as
clearly indicated in Figure 4. The Image HDU is represented by a fits image class and a ASCII
Table HDU or a Binary Table HDU by a fits table class, both of which inherit the fits hdu
class.
The code to access each of these HDU in this internal structure is shown on the left side of
Figure 4. The arrows in the figure show the correspondence between the API structure and theclass structure. To access an HDU you can write “fits.image(...). ...” or “fits.table(..
.). ...” if you know the type of the HDU, or otherwise you can write “fits.hdu(...). ...”. It
goes without saying that you cannot access any information that is specific to a particular HDU
type in the latter case. The argument passed onto hdu(...) etc. is either the sequential numberof the HDU (0-indexed) or the name of the HDU (the value of EXTNAME in the header).

4.2

Structure of FITS header class and header access via API
fits.image("Primary").header("TELESCOP").svalue()fitscc class
User’s Object
fits_image classinherited

fits_hdu classfits_header classfits_header_record class

Imaging Data

fits_header_record classfits_header_record classfits_header_record class

Figure 5: Detailed class structure of the Primary HDU in Figure 4 and example of API thataccesses header records.
Next, let’s take a look at the structure around the FITS header. fits hdu class controls afits header class object that represents the entire FITS header, as shown in Figure 5. In turn,the fits header class controls an array of objects of the fits header record class, each of which
represents one header record.
To use the API to access the content of the header, simply write .header(...). ... after eitherof .image(...), .table(...), or .hdu(...). The argument passed onto .header(...) is either aheader record number (0-indexed) or a header keyword. Please refer to Figure 5 to identify how it
corresponds to the class structure21) .

4.3

Representation of Image HDU

An image HDU is represented by the fits image class, which has an internal structure that only
contains internal objects related to the header and an internal mdarray object for image data.
21)

If you take a closer look at the figure you can see that the API structure has only three tiers from fits
to header(...), whereas the class structure has four tiers from fitscc to fits header record. The lack of a tierin the API is for the sake of less code, but if you feel uncomfortable with that you can also write the code like
this: fits.image(...).header().at(...).svalue(). In this case, .header(), which takes no argument, returns thereference to the fits header class object.

Ver. 1.2.1

31

mdarray is a generic class provided by SLLIB for use in manipulating arrays of n-dimension, andwhich simply contain image data of a FITS Data Unit in the memory buffer as it is22) .
In addition to the member functions of the fits image class, the member functions of mdarrayclass can also be used to read, write, and modify image data. The former are provided for use in
FITS-specific operations from pixel access through to assisting in the primary treatment of celestialbodies, while the latter on generic operations for multi-dimensional arrays such as arithmetic
operations.
The following example accesses pixel values using dvalue(x,y,z) and assign(val,x,y,z),which are member functions of the fits image class. With this code the pixel value at (x, y) in
the image data is copied to (x+1, y).
¨§¥

double value = fits.image(0L).dvalue(x, y);fits.image(0L).assign(value, x+1, y);¦

Image analysis using higher level APIs is also covered in Questions 2 and 3 of §1.1.
Member functions of mdarray can be used via data array(), which is a member function of
the fits image class, as in: image(...).data array().crop(...).

4.4

Representation of ASCII Table HDU and Binary Table HDU

fits.table(1L).col(2L).dvalue(0)fits_table classinherited

fits_hdu class

Main Table Columns

fits_table_colclass

fits_table_col
class

FITS Header

Table Data
fits_table_colclass

fits_header
class

Heap Area mdarray class

Figure 6: Detailed class structure of Binary Table HDU in Figure 4 and example API used toaccess cells in the Binary Table.
With SFITSIO both the ASCII Table HDU and Binary Table HDU are represented by thefits table class. In addition to internal objects that represent the FITS header, the fits tableclass has an array of objects of the fits table col class, which represents one column in its
entirety, and a mdarray object for the Heap Area. For the sake of efficient data access and toeliminate any worry about the alignment the content of the main table are divided into columns
and placed in the buffers belonging to the fits table col class object.
Figure 6 shows the correspondence between the class structure and the API structure; thecolumn in the table is accessible using table(...) followed by .col(...). ....
The Heap Area corresponds to the mdarray class internal object as with the image buffer of
Image HDU. There are only ultra-low level APIs for use with variable-length arrays. In the future
they will be accessible using high-level APIs, however, as in table(...).col(...).dvalue(...).
22)

Only different endian orders get converted.

32

4.5

SFITSIO User’s Reference Guide

System and Notice of FITS Header Management with SFITSIOWith the current version of SFITSIO programmers have to use member functions provided inclasses used to express the FITS data units (e.g., fits image class, fits table class, etc.), rather thanmember functions that rewrite the content of the header, when updating the structure or propertiesof data unit. This then means that header records directly updated using member functions offits header record class in the programmer’s code will not be effective with written FITS files. Anysuch direct updates being permitted could lead to confusion for programmers. Directly updating
header records used for data unit information is therefore prohibited in fits header objects managed
by the fits hdu object23) .
The next table shows the list of header keywords that cannot be updated directly by a programmer’s code. This table also includes the member functions used to update the values. Someof these functions can change the data unit structure, properties, etc.

keywordSIMPLEEXTENDFMTTYPEFTYPEVER
EXTNAMEEXTVER
BITPIXNAXISNAXISn
BSCALE
BZERO
BUNIT
BLANK
XTENSIONPCOUNTGCOUNTTHEAPTFIELDS
TXFLDKWD
TTYPEnTDISPnTBCOLn
TFORMnTDIMn
TZEROnTSCALnTUNITnTNULLnTELEMnTALASn23)

member functions to update––
assign fmttype()
assign ftypever()assign hduname()
assign hduver()image().convert type()
image().increase dim(), etc.
image().resize()image().assign bscale()image().assign bzero()image().assign bunit()
image().assign blank()
table().ascii to binary(), etc.
––
table().resize reserved area()table().append cols(), etc.
table().update col header(), etc.
table().update col header(), etc.
table().update col header(), etc.
table().define a col()table().update col header(), etc.
table().update col header(), etc.
table().update col header(), etc.
table().update col header(), etc.
table().update col header(), etc.
table().update col header(), etc.
table().update col header(), etc.
table().update col header(), etc.

section––§12.3.21§12.3.22§12.3.23§12.3.24§12.6.13§12.6.20§12.6.22§12.6.15§12.6.14§12.6.17§12.6.16§12.8.36––§12.9.11§12.8.46§12.8.41§12.8.41§12.8.41§12.8.38§12.8.41§12.8.41§12.8.41§12.8.41§12.8.41§12.8.41§12.8.41§12.8.41

Strictly speaking, a programmer’s use of member functions provided in the fits header record class can bedetected, and the library routine can update the properties or structure of fits image objects or fits table objects.
However, currently SFITSIO does not have any code for that type of management.

Ver. 1.2.1

4.6

33

Our policy when designing member functions

Designing how member functions are called and how APIs are tiered is almost as important as
designing class structure. Details of the content of member functions can be found in §4.7, andcategorized by their objective for the sake of clarity. Before going into any detail, however, I will
briefly explain our policy when designing the member functions of SFITSIO.
4.6.1

API level

With SFITSIO the member functions that read or write values in the Header Unit or Data Unit
are classified into three levels: high, low, and ultra-low. These levels indicate the extent of theoperations (BZERO, etc) and conversions performed in conformance with the FITS convention;with the higher the level being the greater the number of operations and conversions.
4.6.2

Rules for arguments and return values• Common rules(1) “Length” and “size” are always long.
(2) A string is basically “const char *” or “char *”.
(3) All indices of the HDU, headers, images, or tables and order of dimensions are 0-indexed.
(4) No member function returns the address of a dynamically created object.
• Rules for arguments(1) Classes with the const attribute are always referenced.
(2) When specifying x, y, z, etc. the lowest order dimension comes first.
• Rules for return values(1) With regard to functions that return a number or status, a negative value means anerror has occurred.
(2) With regard to functions that involve file I/O, the value they return reveals their status.
(3) Member functions other than (2) that modify the content of the object (i.e., functions
without the const attribute) always return a reference to themselves.
(3) means it is possible to specify successive operations being used on an image, as in:
¨
§

4.7
4.7.1

¥

fits.image(0L).add(image1).add(image2).add(image3). ... ;¦Member functions categorized by their objective and API level
File I/O

The return value of each member function reveals their status, and return a negative value if theyfail.
Member function[fitscc class]read stream(const char *)write stream(const char *)access stream(const char *)read template(int, const char *)[fits header class]read stream(cstreamio &)write stream(cstreamio &)skip data stream(cstreamio &)Description

Details

Reads a FITS file
Writes a FITS fileReads/writes a FITS file via commands
Reads a template file

§12.3.1§12.3.3§12.3.4§12.3.5

Reads the Header Unit only
Writes the Header Unit only
Skips over one Data Unit

§12.5.1§12.5.2§12.5.3

34

SFITSIO User’s Reference Guide

4.7.2

Initialization and copying of total content

The names of these member functions always include “init”. init() with no argument can beused to free memory areas that have been previously used.

Member function[fitscc class]init()
init(const fitscc &)[fits hdu class]header init()
header init(const fits::header def [])header init(const fits header &)[fits image class]image(...).init()
image(...).init(const fits image &)image(...).init(int, long, long, long)[fits table class]table(...).init()
table(...).init(const fits table &)table(...).init(const fits::table def [])[fits table col class]table(...).col(...).init()
table(...).col(...).init(const fits table col &)4.7.3

Description

Details

Initializes content
Copies content of the object passedin§12.3.15§12.3.15

Initializes the header
Initializes and configures
header
Copies content of the header§12.4.25§12.4.25

the§12.4.25

Initializes content
Copies content of the object passed
in
Initializes with the type and size

§12.6.18§12.6.18

Initializes content
Copies content of the object passed
in
Initializes according to the column
definitions in the argument§12.8.34§12.8.34

Initializes content
Copies content of the object passed
in§12.8.35§12.8.35§12.6.18§12.8.34

Swapping the entire content

The names of these member functions always include “swap”. Reserved keywords that concern thecontent of the Data Unit cannot be swapped within the header.

Member function[fits hdu class]header swap()[fits image class]image(...).swap(fits image &)[fits table class]table(...).swap(fits table &)[fits table col class]table(...).col(...).swap(fits table col &)Description

Details

Swaps the entire content apart fromreserved keywords§12.4.26

Swaps content§12.6.19

Swaps content§12.8.45

Swaps content§12.8.60

Ver. 1.2.1
4.7.4

35

Aquisition of data type

The names of these member functions always include “type”. For constants in the return valuerefer to §12.1.
Member function[fits hdu class]hdu(...).hdutype()[fits header record class]hdu(...).header(...).type()[fits image class]image(...).type()[fits table col class]table(...).col(...).type()table(...).col(...).heap is used()table(...).col(...).heap type()

4.7.5

Return value

Details

Type of the HDU§12.3.13

Type of header record§12.4.13

Type of image data

§12.6.5

Type of table column
Whether the array is variable-length
Data type of variable-length array§12.8.8§12.8.9§12.8.10

Retrieval of the length or size

The names of these member functions always include “bytes” or “length”. All return values areof type long.
Member function[fitscc class]length()stream length()[fits hdu class]hdu(...).header length()[fits image class]image(...).dim length()image(...).length()image(...).length(long)
image(...).bytes()
image(...).col length()image(...).row length()image(...).layer length()[fits table class]table(...).col length()table(...).row length()[fits table col class]table(...).col(...).bytes()
table(...).col(...).elem byte length()table(...).col(...).elem length()table(...).col(...).dcol length()table(...).col(...).drow length()table(...).col(...).heap bytes()
table(...).col(...).max array length()table(...).col(...).array length(long)

Return value

Details

Number of HDUs
Byte length of output uncompressed
FITS file§12.3.7§12.3.6

Number of header records§12.4.1

Number of dimensions
Complete number of pixels
Number of pixels in the dimensions specified by the argument
Byte length of single pixel
Pixel width of image
Pixel height of image
Number of layers§12.6.3§12.6.4§12.6.4

Number of columns (fields)
Number of rows

§12.8.3§12.8.4

Byte length of an element in the column
Byte length of the column
Number of elements in the column
Number of columns in a multidimensional array
Number of rows in a multi-dimensionalarray
Byte length of an element in a variablelength array
Maximum length of a variable-length array
Length of the row specified by the argument in a variable-length array§12.8.11§12.8.12§12.8.13§12.8.14§12.6.6§12.6.7§12.6.8§12.6.9§12.8.15§12.8.16§12.8.17§12.8.18

36

SFITSIO User’s Reference Guide

4.7.6

Retrieval of index for internal object array

Although you can quickly access table columns etc. by name, thanks to the internal search mechanisms, you may wish to use index in an internal object array if you are particularly performanceconscious, for example, large number of accesses in a loop. To accomplish that you will need toacquire the index for the name beforehand using the following member functions. These take thename as an argument and return the index in an internal object array (long and 0-indexed). They
return a negative number if the argument does not match, and therefore they are often used toverify its existence.
Member function[fitscc class]index( const char * )[fits hdu class]hdu(...).header index( const char * )[fits table class]table(...).col index( const char * )4.7.7

Index for the HDU§12.3.14

Index for the header record§12.4.2

Index for the table column§12.8.6

Retrieval/configuration of the name or the version of a construct

Member function[fitscc class]fmttype()assign fmttype(...)
ftypever()assign ftypever(...)[fits hdu class]hdu(...).hduname()
hdu(...).assign hduname(...)
hdu(...).hduver()hdu(...).assign hduver(...)
hdu(...).hduver is set()hdu(...).hdulevel()hdu(...).assign hdulevel(...)
hdu(...).hdulevel is set()[fits table col class]table(...).col(...).name()table(...).col(...).assign name(...)

4.7.8

Return value

Description

Details

Returns the value of FMTTYPE (string)
Sets the value of FMTTYPE
Returns the value of FTYPEVER (integer)
Sets the value of FTYPEVER§12.3.8§12.3.21§12.3.9§12.3.22

Returns the name of the HDU (the value of
EXTNAME; string)
Sets the name of the HDU (the value of
EXTNAME; string)
Returns the version of the HDU (the valueof EXTVER; integer)
Sets the version of the HDU (the value of
EXTVER; integer)
Verifies the existence of the version of the
HDU (the value of EXTVER; integer)
Returns the level of the HDU (the value of
EXTLEVEL; integer)
Sets the level of the HDU (the value of
EXTLEVEL; integer)
Verifies the existence of the level of the HDU(the value of EXTLEVEL; integer)§12.3.10

Returns the name of the column
Sets the name of the column§12.3.23§12.3.11§12.3.24§12.3.26§12.3.12§12.3.25§12.3.27§12.8.7§12.8.37

Data reading (high level)

These member functions perform FITS-specific operations and convert the type of values into what
to be returned and are typically used by the SFITSIO programmers to read data.
With string values in the header the quotation marks and blank characters on both sides are
removed, the quotation marks in the string converted from “’’” to “’”, and the resulting string
then returned.

Ver. 1.2.1

37

When retrieving values from the Data Unit, the values of BZERO, BSCALE, TZEROn, and TSCALn
in the header are taken into account. In addition, the functions dvalue(), svalue(), andget svalue() return NaN or the NULL string, which defaults to "NULL"24) , for the case where
the data value equals the value of either BLANK or TNULLn in the header, respectively.

• Reads and returns data
The name of the member function is always dvalue(), lvalue(), llvalue(), bvalue(), or
svalue(), and which returns type double, long, long long, bool, or string (const char*), respectively.
Member function[fits header record class]hdu(...).header(...).dvalue()hdu(...).header(...).lvalue()hdu(...).header(...).llvalue()hdu(...).header(...).bvalue()hdu(...).header(...).svalue()[fits image class]image(...).dvalue(long,long,long)
image(...).lvalue(long,long,long)
image(...).llvalue(long,long,long)[fits table col class]table(...).col(...).dvalue(...)
table(...).col(...).lvalue(...)
table(...).col(...).llvalue(...)
table(...).col(...).bvalue(...)
table(...).col(...).svalue(...)

Type of return value

Details

doublelong
long longbool
const char *§12.4.6§12.4.7§12.4.7§12.4.8§12.4.4

doublelong
long long§12.6.10§12.6.11§12.6.11

doublelong
long longbool
const char *§12.8.20§12.8.21§12.8.21§12.8.22§12.8.23• Reads and stores the data in a buffer passed in as an argument
The name of the member function is “get svalue()”. It stores the string value to a buffer
passed in as an argument.
Member function[fits header record class]hdu(...).header(...).get svalue(char *, size t)[fits table col class]table(...).col(...).get svalue(long, char *, size t), etc.

4.7.9

Details§12.4.5§12.8.24

Data writing (high level)

The name of the member function is always “assign()”. These member functions perform FITSspecific operations and type conversions and then store the resulting values in the data buffer of
FITS, and are typically used by SFITSIO programmers to write data.
With string values in the header the quotation marks get appended on both sides, and thequotation marks in the string converted from “’” to “’’”.
24)

the NULL string can be configured with table(...).assign null svalue(...); for more details refer to §12.8.29.

38

SFITSIO User’s Reference Guide

When writing values into the Data Unit, the values of BZERO, BSCALE, TZEROn, and TSCALn
in the header are taken into account. In addition, if NaN or the NULL string, which defaults to"NULL"25) , is passed in as the argument of either a floating point value or a string value, the valueof BLANK or TNULLn in the header respectively is stored.

Member function[fits header record class]hdu(...).header(...).assign(...)[fits image class]image(...).assign(...)[fits table col class]table(...).col(...).assign(...)

25)

Details§12.4.9§12.6.12§12.8.25

the NULL string can be configured using table(...).assign null svalue(...); for more details refer to§12.8.29.

Ver. 1.2.1
4.7.1039

Data reading (low level)

These member functions convert the type of values into what to be returned without performing
any FITS-specific operations, and which can be used if there is no BZERO, BSCALE, BLANK, TZEROn,
TSCALn, or TNULLn settings in the header or if maximum performance is required (if the utmost
performance is required at any cost you may wish to use an ultra-low level API). They are themost effective when the data type of the member function matches the type of the FITS data (thebit type needs a somewhat large amount of operations, though).
With the string values in the header the quotation marks on either side do not get removed.
The saved data values are retrieved without any operations as with BZERO or BLANK when retrieving
the values from the Data Unit.

• Reads and returns data
The name of the member function is simply value() if it reads from the header, with thename being fully qualified by the return type, as with double value(), long value(), if thefunction reads from the Data Unit.
Member function[fits header record class]hdu(...).header(...).value()[fits image class]image(...).double value(long,long,long)
image(...).float value(long,long,long)
image(...).longlong value(long,long,long)
image(...).long value(long,long,long)
image(...).short value(long,long,long)
image(...).byte value(long,long,long)[fits table col class]table(...).col(...).double value(...)
table(...).col(...).float value(...)
table(...).col(...).longlong value(...)
table(...).col(...).long value(...)
table(...).col(...).short value(...)
table(...).col(...).byte value(...)
table(...).col(...).logical value(...)
table(...).col(...).bit value(...)
table(...).col(...).string value(...)
table(...).col(...).array heap offset(...)

Type of return value

Details

const char *§12.4.17

doublefloat
long long
long
short
unsigned char

§12.7.5§12.7.6§12.7.7§12.7.8§12.7.9§12.7.10

doublefloat
long long
long
short
unsigned char
int
long
const char *long§12.9.17§12.9.16§12.9.14§12.9.13§12.9.12§12.9.15§12.9.19§12.9.18§12.9.20§12.9.21• Reading and storing the data in the buffer passed in as an argument
The name of the member function is “get value()” if it operates on the header, and“get string value()” if it operates on the Data Unit. In either case it stores the stringvalue in the buffer passed in as an argument.
Member function[fits header record class]hdu(...).header(...).get value(char *, size t)[fits table col class]table(...).col(...).get string value(long, char *, size t), etc

Details§12.4.18§12.9.22

40
4.7.11SFITSIO User’s Reference Guide
Data writing (low level)

These member functions perform type conversions into a FITS data type and store the resulting
values in the data buffer without performing any FITS-specific operations, and which can be used if
there is no BZERO, BSCALE, BLANK, TZEROn, TSCALn, or TNULLn settings in the header or if maximum
performance is required (if the utmost performance is required at any cost you may wish to use
an ultra-low level API). They are the most effective when the data type of the member function
matches the type of the FITS data (the bit type needs a somewhat large amount of operations,though).
With the string values in the header the quotation marks on either side do not get appended.
Values are written to the Data Unit without any operations as with BZERO or BLANK.

Member function[fits header record class]hdu(...).header(...).assign value(...), etc.
[fits image class]image(...).assign double(...)
image(...).assign float(...)
image(...).assign longlong(...)
image(...).assign long(...)
image(...).assign short(...)
image(...).assign byte(...)[fits table col class]table(...).col(...).assign double(...)
table(...).col(...).assign float(...)
table(...).col(...).assign longlong(...)
table(...).col(...).assign long(...)
table(...).col(...).assign short(...)
table(...).col(...).assign byte(...)
table(...).col(...).assign logical(...)
table(...).col(...).assign bit(...)
table(...).col(...).assign string(...)
table(...).col(...).assign arrdesc(...)

Details§12.4.21§12.7.11§12.7.12§12.7.13§12.7.14§12.7.15§12.7.16§12.9.28§12.9.27§12.9.25§12.9.24§12.9.23§12.9.26§12.9.30§12.9.29§12.9.31§12.9.32

Ver. 1.2.1
4.7.12

41

Data access (ultra-low level)

These high-risk-high-return member functions directly read/write raw byte data in the Data Unit.
Because the different endian orders get converted and the alignment adjusted for the processing
system within the buffer of an object, apart from the Heap Area in a binary table, you can immediately access the data as soon as the address in the pointer variable is of the correct type. WithSFITSIO, there are definitions for data types that are used in FITS files (such as fits::logical t
and fits::double t), that can be used to declare pointer variables (for the definition of the types
refer to §12.2).

You can use these member functions when in pursuit of maximum performance but type checks
are left up to programmers with regard to the functions that exchange data with the type void *;if you do not understand the connotations they can have unexpected effects. And hence you should
be forewarned.

42

SFITSIO User’s Reference Guide

The names for these member functions are get data(), put data(), data ptr(), and typename ptr(), as well as get heap(), put heap(), and heap ptr() for the Heap Area of the Binary
Table. Please note that different endian orders do not get converted (theoretically impossible) inthe data buffers of the Heap Area, which can be arbitrarily aligned. Extreme caution is therefore
required with the reading or writing of data of the type larger than one byte. API functions forvariable-length arrays are summarized in §4.7.21.

Member function[fits image class]image(...).get data(...)
image(...).put data(...)
image(...).byte t ptr(...)
image(...).short t ptr(...)
image(...).long t ptr(...)
image(...).longlong t ptr(...)
image(...).float t ptr(...)
image(...).double t ptr(...)
image(...).data ptr(...)[fits table col class]table(...).col(...).get data(...)
table(...).col(...).put data(...)
table(...).col(...).bit t ptr(...)
table(...).col(...).byte t ptr(...)
table(...).col(...).logical t ptr(...)
table(...).col(...).ascii t ptr(...)
table(...).col(...).short t ptr(...)
table(...).col(...).long t ptr(...)
table(...).col(...).longlong t ptr(...)
table(...).col(...).float t ptr(...)
table(...).col(...).double t ptr(...)
table(...).col(...).complex t ptr(...)
table(...).col(...).doublecomplex t ptr(...)
table(...).col(...).longarrdesc t ptr(...)
table(...).col(...).llongarrdesc t ptr(...)
table(...).col(...).data ptr()[fits table class]table(...).get heap(...)
table(...).put heap(...)
table(...).heap ptr()

Description

Details

Retrieves byte data to the buffer passed in as
an argument
Writes data in the buffer passed in as an argument
Retrieves the address of the internal buffer(type: fits::byte t *)Retrieves the address of the internal buffer(type : fits::short t *)Retrieves the address of the internal buffer(type: fits::long t *)Retrieves the address of the internal buffer(type: fits::longlong t *)Retrieves the address of the internal buffer(type: fits::float t *)Retrieves the address of the internal buffer(type: fits::double t *)Retrieves the address of the internal buffer(type: void *)§12.7.3

These functions are for use with the column
data area in the main table.

§12.9.3§12.7.4§12.7.2§12.7.2§12.7.2§12.7.2§12.7.2§12.7.2§12.7.2§12.9.4§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2§12.9.2
These functions are for use with the Heap
Area of the Binary Table.

§12.9.6§12.9.7§12.9.5

Ver. 1.2.1
4.7.1343

Conversion between data types

These member functions quickly convert the different types of numerical data into each other.
convert type() with the Binary Table only converts columns of the numerical type, apart fromvariable-length arrays.

Member function[fits image class]image(...).convert type(...)[fits table col class]table(...).col(...).convert type(...)

4.7.14

Description

Details

Converts the object into an image of thespecified type, ZERO values, SCALE values, and BLANK values§12.6.13

Converts the object into a column of thespecified type, ZERO values, SCALE values, and NULL values§12.8.28

Member functions that operate on ZERO/SCALE/BLANK/UNIT values

For modifying TDIMn, etc. in binary tables and ASCII tables refer to §4.7.19.

Member function[fits image class]image(...).bzero()image(...).assign bzero()image(...).bscale()image(...).assign bscale()image(...).blank()
image(...).assign blank()
image(...).bunit()
image(...).assign bunit()[fits table col class]table(...).col(...).tzero()table(...).col(...).assign tzero()table(...).col(...).tscal()table(...).col(...).assign tscal()table(...).col(...).tnull()table(...).col(...).assign tnull()table(...).col(...).tunit()
table(...).col(...).assign tunit()

Description

Details

Retrieves the BZERO value
Sets the BZERO value
Retrieves the BSCALE value
Sets the BSCALE value
Retrieves the BLANK value
Sets the BLANK value
Retrieves the BUNIT value
Sets the BUNIT value§12.6.14§12.6.14§12.6.15§12.6.15§12.6.16§12.6.16§12.6.17§12.6.17

Retrieves the TZERO value
Sets the TZERO value
Retrieves the TSCAL value
Sets the TSCAL value
Retrieves the TNULL value
Sets the TNULL value
Retrieves the TUNIT value
Sets the TUNIT value§12.8.30§12.8.30§12.8.31§12.8.31§12.8.32§12.8.32§12.8.33§12.8.33

44

SFITSIO User’s Reference Guide

4.7.15

Data editing

These functions are used to modify the size of the buffer area or append, insert, or remove elements.
These functions have consistent names such as resize, append, insert, or erase. Some of theclasses, however, include differently named member functions.

Member function[fitscc class]append image(...)
append table(...)
insert image(...)
insert table(...)
erase(...)[fits hdu class]hdu(...).header append records(...)
hdu(...).header append(...)
hdu(...).header insert records(...)
hdu(...).header insert(...)
hdu(...).header erase records(...)
hdu(...).header erase(...)
hdu(...).header update(...)
hdu(...).header assign(...)
hdu(...).header(...).assign comment(...)

hdu(...).header rename(...)[fits image class]image(...).increase dim(...)
image(...).decrease dim(...)
image(...).resize(...)
image(...).assign default(...)
image(...).data array().crop(...), etc

Description

Details

Appends an Image HDU
Appends an ASCII Table or Binary Table
HDU
Inserts an Image HDU
Inserts an ASCII Table or Binary Table
HDU
Removes an HDU§12.3.16§12.3.17

Appends multiple header records
Appends a single header record
Inserts multiple header records
Inserts a single header record
Removes multiple header records
Removes a single header record
Appends or updates a single record
Updates a single record
Sets a comment for a header record
Modifies the keyword for a single header
record

§12.4.27§12.4.28§12.4.29§12.4.30§12.4.31§12.4.32§12.4.23§12.4.24§12.4.22§12.4.33

Increases the dimensions
Decreases the dimensions
Modifies the size of each dimension
Sets the pixel value of new elements createdby .resize(), etc.
Uses member functions of the mdarrayclass to edit the image. See also §4.7.17.

§12.6.20§12.6.21§12.6.22§12.6.23§12.3.18§12.3.19§12.3.20§12.7.1

Ver. 1.2.1
Member function[fits table class]table(...).resize rows(...)
table(...).append rows(...)
table(...).insert rows(...)
table(...).erase rows(...)
table(...).clean rows(...)
table(...).move rows(...)
table(...).swap rows(...)
table(...).import rows(...)
table(...).append cols(...)
table(...).append a col(...)
table(...).insert cols(...)
table(...).insert a col(...)
table(...).swap cols(...)
table(...).erase cols(...)
table(...).erase a col(...)
table(...).copy(...)
table(...).assign null svalue(...)
table(...).ascii to binary()[fits table col class]table(...).col(...).move(...)
table(...).col(...).swap(...)
table(...).col(...).clean(...)
table(...).col(...).import(...)
table(...).col(...).assign default(...)

45
Description

Details

Modifies the length of the row
Appends rows
Inserts rows
Remove rows
Initializes rows
Copies rows
Interchanges rows
Imports a table
Appends multiple columns
Appends a single column
Inserts multiple columns
Inserts a single column
Interchanges columns
Removes multiple columns
Removes a single column
Copies to another object
Sets the NULL string for use in a highlevel API
Converts an ASCII table to a Binary table§12.8.51§12.8.52§12.8.53§12.8.54§12.8.55§12.8.56§12.8.57§12.8.58§12.8.46§12.8.46§12.8.47§12.8.47§12.8.48§12.8.49§12.8.49§12.8.50§12.8.29

Copies between rows in a column
Interchanges rows in a column
Initializes values in a column
Imports to a specific column
Sets the cell value of new elements created by .resize rows(), etc.

§12.8.59§12.8.60§12.8.61§12.8.62§12.8.63§12.8.36

46

SFITSIO User’s Reference Guide

4.7.16

Member functions used to process images

You can use member functions that can call user-defined functions used to process pixels in rectangular areas easier and faster than loops written in programming code. The values of pixels
passed onto user functions are floating-point real numbers that have already been converted using BZERO/BSCALE/BLANK values and hence any code that is not essential to the intended
operation can be minimized.

Member function[fits image class]image(...).fix rect args(...)

Description

Checks and modifies the value of the argument that specifies the area given to.scan cols(), etc., in thereby ensuring
it fits within the boundary of the image
in the object
image(...).scan cols(double [], ...)
Horizontally scans the specified area using a user-defined function
image(...).scan rows(double [], ...)
Vertically scans the specified area usinga user-defined function
image(...).scan layers(double [], ...)
Layer scans the specified area using auser-defined function
image(...).fill(double, ...)
Modifies pixel values in the specified
area to a single value
image(...).fill(double, void (*)(...), ...)
Fills the specified area with the return
value of the user-defined function
image(...).add(double, ...)
Adds a single value to the pixel values
in the specified area
image(...).subtract(double, ...)
Subtracts a single value from the pixel
values in the specified area
image(...).multiply(double, ...)
Multiplies pixel values in the specified
area by a single value
image(...).divide(double, ...)
Divides pixel values in the specified areaby a single value
image(...).copy(fits image *, ...)
Copies the specified area to anotherfits image object
image(...).cut(fits image *, ...)
Copies the specified area to anotherfits image object and erases the pertinent area in the original image
image(...).paste(const fits image &, ...)
Pastes an image from anotherfits image object
image(...).paste(const fits image &, void (*)(...), ...) Pastes
an image from anotherfits image object, after having beenprocessed by a user-defined function
image(...).add(const fits image &, ...)
Adds an images from anotherfits image object
image(...).subtract(const fits image &, ...)
Subtracts an image from anotherfits image object
image(...).multiply(const fits image &, ...)
Multiplies the image by a one from another fits image object
image(...).divide(const fits image &, ...)
Divides the image by a one from anotherfits image object

Details§12.6.24§12.6.25§12.6.26§12.6.27§12.6.28§12.6.33§12.6.29§12.6.30§12.6.31§12.6.32§12.6.34§12.6.34§12.6.35§12.6.40§12.6.36§12.6.37§12.6.38§12.6.39

Ver. 1.2.1
4.7.17

47

Member functions of the mdarray class that can be used to edit images

FITS image data can be edited using the member functions of fits image class and mdarray class.
Some member functions of the mdarray class will be covered here. Refer to the SLLIB manual orcomments in the mdarray.h header file.

Member function[mdarray class]image(...).data array().swap(...)
image(...).data array().move(...)
image(...).data array().cpy(...)
image(...).data array().insert(...)
image(...).data array().crop(...)
image(...).data array().erase(...)
image(...).data array().round(), etc.

4.7.18Description
Interchanges interval data of the specified dimensions
Copies interval data of the specified dimensions
Copies interval data of the specified dimensions (thebuffer size is modified as needed)
Inserts blank data of the specified dimensions
Extracts an interval of the specified dimensions
Removes an interval of the specified dimensions
Iterates over all pixels to perform an operationand store the results. Available operations include.ceil(), .floor(), .round(), .trunc(), and .abs().

Member functions for use in image analysis

fits header record class and fits image class provide member functions that have essential primary
image reduction functionality. See also tools/stat pixels.cc and tools/combine images.cc in
the SFITSIO package.

Member function[fits header record class]hdu(...).header(...).get section info(...)[fits image class]image(...).stat pixels(...)

image(...).combine layers(...)

Description

Details

Retrieves information about rectangular areas in the IRAF format (suchas BIASSEC) within the FITS header§12.4.36

Calculates the average, standard deviation, and median etc. of the specified area
Combines the specified area of the 3D
image with average or median§12.6.41§12.6.42

48

SFITSIO User’s Reference Guide

4.7.19

Member functions that operate on column definitions of tables

The following member functions with “col header” can handle both reserved keywords (such as
TDISPn) and non-reserved keywords (such as TLMAXn) with respect to column definitions in an
ASCII Table or Binary Table. As shown in the example below the column name (or index) andthe name of the keyword can be specified using separate arguments, thus eliminating the need forsnprintf() to be used to concatenate the keyword with n.
¨§¥/* Modifies the TUNUT value and comment of the column "R-BAND"
within the "EVENT" table */fits.table("EVENT").update_col_header("R-BAND", "TUNIT","mag", "absolute magnitude");¦Modifying the value of a reserved keyword results in the data in the object being automatically
updated. In the case of a non-reserved keyword TXFLDKWD will also be automatically updated (referto §10.7 for more details on TXFLDKWD).
The define(...) member function uses a structure fits::table def to modify the value ofa reserved keyword.

Member function[fits table class]table(...).col header index(...)
table(...).col header(...).svalue(), etc.
table(...).update col header(...)
table(...).erase col header(...)
table(...).rename col header(...)
table(...).sort col header()[fits table col class]table(...).col(...).definition()table(...).col(...).define(...)

Description

Details

Returns the index to the header record
with the specified column definition
Accesses the header record with thespecified column definition
Modifies a single header record of a column definition
Removes a single header record of a column definition
Modifies the name of the user-definedheader keyword for columns
Sorts header keywords of columns intheir order§12.8.39

Reads a single column definition
Modifies a single column definition§12.8.19§12.8.38§12.8.40§12.8.41§12.8.42§12.8.43§12.8.44

Ver. 1.2.1
4.7.20Special member functions used for processing headersFunction or member function[fits hdu class]hdu(...).header(...).status()hdu(...).header(...).keyword()
hdu(...).header(...).get keyword(...)
hdu(...).header(...).comment()
hdu(...).header(...).get comment(...)
hdu(...).header regmatch(...)
hdu(...).header(...).assign system time()
hdu(...).header formatted string()
hdu(...).header fill blank comments()

hdu(...).header assign default comments()[Function]
fits::update comment dictionary(...)

4.7.2149

Description

Details

Retrieves the status of the header
recordRetrieves the keyword of the header
recordRetrieves the keyword of the header
recordRetrieves the comment of the header
recordRetrieves the comment of the header
recordSearches for keywords with the regular expression
Sets the current time (UTC) using
the “yyyy-mm-ddThh:mm:ss” format
Returns the header string formatted
for FITS files
Fills the comment field with the content of the header comment dictionary in SFITSIO if no comment exists
Fills the comment field with the content of the header comment dictionary in SFITSIO regardless ofwhether a comment already exists§12.4.14

Appends or updates the content of
the comment dictionary§12.4.15§12.4.16§12.4.19§12.4.20§12.4.3§12.4.37§12.4.35§12.4.38§12.4.39§12.4.40

Member functions used on variable-length arrays in binary tables (low-level
APIs)

Variable-length arrays are not supported by the high-level API in the current version of SFITSIO
and hence the following low-level API functions have to be used. See also the sample code in
test/access bte heap.cc and sample/create vl array.cc in the source package of SFITSIO.

50

SFITSIO User’s Reference Guide
Function or member function[fits table class]table(...).get heap(...)
table(...).put heap(...)
table(...).heap ptr()
table(...).heap length()table(...).resize heap()
table(...).reverse heap endian()table(...).reserved area length()table(...).resize reserved area()[fits table col class]table(...).col(...).heap is used()table(...).col(...).heap type()table(...).col(...).heap bytes()
table(...).col(...).max array length()table(...).col(...).array length(long)table(...).col(...).array heap offset(...)
table(...).col(...).assign arrdesc(...)

Description

Details

These functions are for use with theHeap Area of the Binary Table.

§12.9.6

Returns the byte length of the Heap
Area
Modifies the size of the Heap Area
Converts the endian orders of the
Heap Area
Returns the byte length of the reserved area
Modifies the size of the reserved area
Determines whether the column is avariable-length array
Determines the data type of thevariable-length array
Determines the byte length of an element of a variable-length array
Returns the maximum size of avariable-length array
Returns the length of a variablelength array of the row specified by
the argument
Returns the position in the heap of
the variable-length array concerned
Sets a array descriptor for a variablelength array§12.9.7§12.9.5§12.8.5§12.9.8§12.9.9§12.9.10§12.9.11§12.8.9§12.8.10§12.8.16§12.8.17§12.8.18§12.9.21§12.9.32

Ver. 1.2.1

551

Tutorial

We would like to introduce you to the easy going world of SFITSIO using some simple examples.

5.1

First Incantation

Write the following code at the top of your source code if using SFITSIO.
¨#include <sli/fitscc.h>using namespace sli;

§

5.2

¥
¦

Read/Write files

You can read and write files using the member functions of read stream() and write stream(),respectively.
In the below example the program reads the file specified by the first argument in a command
line, outputs the HDU information, and writes all the content of the file that was read into the filespecified by the second argument. First, the code without error handling is shown.
¨¥

int main( int argc, char *argv[] ){long i;fitscc fits;/* object "fits" */fits.read_stream(argv[1]);/* reading FITS file */for ( i=0 ; i < fits.length() ; i++ ) {/* output HDU info */printf("HDU %ld : hduname = %s\n", i, fits.hduname(i));}
fits.write_stream(argv[2]);/* writing FITS file */return 0;}§¦#include <stdio.h>#include <sli/fitscc.h>using namespace sli;¨

Compile and run the program. It can be compiled the easiest using s++.

$ s++ fits_io.cc -lsfitsio
g++ -I/usr/local/include -L/usr/local/lib -Wall -O fits_io.cc -o fits_io -lsfits
io -lsllib -lz -lbz2 -lreadline -lcurses$ ./fits_io in.fits out.fits
HDU 0 : hduname = Primary

§

¥

¦

Second, the following code is modified for ensuring error handling. Programmers generally
do not need to allocate memory when using SFITSIO and hence minimum error handling is required26) . You, however, will need to handle any errors using the return values of member functions
that input/output files.
26)

With SFITSIO any failure with memory allocation causes the program to display the reason using the standarderror output and to abort.

52

SFITSIO User’s Reference Guide¨¥#include <stdio.h>#include <sli/fitscc.h>using namespace sli;
int main( int argc, char *argv[] ){int return_status = -1;
fitscc fits;
ssize_t sz;/* object "fits" */if ( 1 < argc ) {long i;const char *in_file = argv[1];sz = fits.read_stream(in_file);/* reading FITS file */if ( sz < 0 ) {/* error handling */fprintf(stderr,"[ERROR] fits.read_stream() failed\n");goto quit;}/* display HDU information */for ( i=0 ; i < fits.length() ; i++ ) {fprintf(stderr,"HDU %ld : hduname = %s\n",i,fits.hduname(i));}}
if ( 2 < argc ) {const char *out_file = argv[2];sz = fits.write_stream(out_file);/* writing FITS file */if ( sz < 0 ) {/* error handling */fprintf(stderr,"[ERROR] fits.write_stream() failed\n");goto quit;}}
return_status = 0;
quit:
return return_status;}§¦

See also sample/read_and_write.cc in the SFITSIO source package.

5.3

Directly accessing remote FITS files via a network

You can use read_stream() and write_stream() to access remote files via a network. In thiscase, however, you will need to specify the path names beginning with http:// or ftp:// in theargument of the member functions.
The following example reads a file from a web server.
¨§¥

sz = fits.read_stream("http://www.xxx.jp/fits_data/foo.fits.bz2");

Although the library can only be used to read from web servers it can also write to FTP servers.
¨§

sz = fits.write_stream("ftp://user:passwd@myhost.jp/home/user/foo.fits.gz");¦¥¦

In this way the argument can include the username and password used to access the FTP
server. Omission of the the username and password results in anonymous access.

Ver. 1.2.1

5.4

53

Read/Write using pipe-connections to make commands (e.g., compression
tools)

Pipe-connections can be used to read or write a FITS file via any special network or to store themwith any special compression format if the commands for the special network/compression support
stdin and stdout.
You can use access_stream() and accessf_stream() (§12.3.4) to access files via some commandline tools. In this case you need to set commands that include path names in the style of open()of Perl to the argument of the member function.
The following example reads a special compressed file using the funpack command.
¨§¥

sz = fits.access_stream("funpack -S foo0.fits.fz |");The next example is used to write a special compressed file.
¨§

sz = fits.access_stream("| fpack - foo1.fits.fz");¦¥¦

Examples in §12.3.4 show the case of reading FITS using HTTP over SSL.

5.5

Basis of accessing headers

Note that the formation of the API directly reflects the structure of FITS files. For example, write
the following to read the value of TELESCOP in Primary header.
¨§¥

printf("TELESCOP = %s\n", fits.hdu("Primary").header("TELESCOP").svalue());¦

Reading values uses the following: dvalue(), lvalue(), llvalue(), bvalue(), and svalue()(§12.4.4–). These functions correspond to the double, long, long long, bool, and const char * types,
respectively.
Member functions, including assign(), and assign comment(), are used to write data, add a
new record to a header, and to update values and comments (§12.4.9–).
¨§¥fits.hdu("Primary").header("TELESCOP").assign("HST").assign_comment("Telescope Name");fits.hdu("Primary").headerf("OBJECT%d",n).assignf("%s-%d",obj[i],j).assignf_comment("Name of the object No.%d",n);¦A convenient feature is that the same style as printf() of libc can be used anywhere. Adding
commentary records such as HISTORY is simple. A member function header append needs twoarguments, as follows.
¨§¥

fits.hdu("Primary").header_append("HISTORY","step-0: done.");¦The Primary HDU is always treated as an image and hence fits.hdu(...) can be replacedwith fits.image(...).
See also sample/read_header.cc in the SFITSIO source package.

5.6

Keyword search in headers (POSIX Extended Regular Expression)

Keyword searches with regular expressions are available for manipulating FITS headers, including
the WCS. The following code is an example of searching the header records in a primary HDU ofwhich the keyword begins with CRVAL1 or CRVAL2. The keywords and raw values are displayedusing header( ... ).keyword() and header( ... ).value()(§12.4.17).

54

SFITSIO User’s Reference Guide

¨

§

¥

fits_image &primary = fits.image("Primary");
long i = 0;
while ( 0 <= (i=primary.header_regmatch(i,"^CRVAL[1-2]")) ) {printf("%s = %s\n",primary.header(i).keyword(),primary.header(i).value());
i++;
}

¦

In the example “fits_image &primary = ...” is a variable, called a reference or alias, andintroduced in C++. This MACRO-like simple mechanism provides for the definition using anothername. Using a reference can shorten the code. More details are available in §6.3.

5.7

Editing headers

Member functions that initialize the header (§12.4.25), add (§12.4.27), insert (§12.4.29), and delete(§12.4.31) the records of the header are available for use. The functions used to edit headers candeal with many records at one time via structures (See the example in §5.9).
The following code shows an example of all the content of the header records in one FITS being
copied to another.
¨§¥

fits_out.image("Primary").header_append_records( fits_in.image("Primary").header() );¦The .header() with no argument represents the entire header. In the same manner it can beprovided to the member functions of header_init() (§12.4.25) and header_insert_records()(§12.4.29).
To copy only a single header record and not all the content write the following.
¨
§

5.8

¥

fits_out.image("Primary").header_append( fits_in.image("Primary").header("TELESCOP") );¦Accessing image data

The dimensions of the pixels can be obtained using col_length(), row_length, and layer_length()(§12.6.7 -).
¨§¥

printf("Num. of Columns: %ld\n",fits.image("Primary").col_length());
printf("Num. of Rows
: %ld\n",fits.image("Primary").row_length());
printf("Num. of Layers : %ld\n",fits.image("Primary").layer_length());¦

Each of dvalue(), lvalue(), and llvalue() can be used to read and assign() to write(§12.6.10 -). These functions transform the values according to the values of BZERO or BSCALE in
the header.
The function dvalue() reads the value in type double independently of the type of image data.
The coordinate value begins from 0.
¨§

double pixel_val;
pixel_val = fits.image("Primary").dvalue(x,y,z);fits.image("Primary").assign(pixel_val,x1,y1,z1);¥/* Read *//* Write */¦Of course, integer values can be used in read and write operations. The functions lvalue()and llvalue() return long and long long values, respectively.

Ver. 1.2.1
¨

§

5.9

long pixel_val;
pixel_val = fits.image("Primary").lvalue(x,y,z);fits.image("Primary").assign(pixel_val,x1,y1,z1);

55¥/* Read *//* Write */¦Creating new FITS image

This is an example of creating a new image file using data obtained by the CASSIOPEIA telescope.
The sample programs of create_image.cc and create_image_and_header.cc can be found in
the sample directory of the distributed package.
The member function append_image() (§12.3.16) is used to create an image HDU. An example
is shown below where the type of data is a 1024 × 1024 array of double.
¨§

fitscc fits;
fits::header_def defs[] = { {"TELESCOP", "’CASSIOPEIA’", "Telescope name"},{"OBSERVAT", "’NAOJ’", "Observatory name"},{"RA","", "[deg] Target position"},{"DEC","", "[deg] Target position"},{"COMMENT", "-------------------------------"},{NULL} };/* Create Image HDU (Primary) */fits.append_image("Primary",0, FITS::DOUBLE_T,1024,1024);/* Initialize header */fits.image("Primary").header_init(defs);¥¦

It’s ready to be used. With SFITSIO header keywords can be prepared as a structure. In addition, many header records can be assigned at once using member functions such as header_init()(§12.4.25).
The function image().assign() can be used to set the pixel values. If necessary the valuesof BZERO and BSCALE can be set with image().assign_bzero() and image().assign_bscale()(§12.6.14 -), respectively, and the pixel values initialized to zero with image().fill() (§12.6.28).
¨

§

5.10

¥

fits.image("Primary").assign_bzero(32768);
fits.image("Primary").assign_bscale(1);fits.image("Primary").fill(0);¦Copying and pasting image data

The member functions of copy() and paste() can be used to copy and paste rectangular regions(§12.6.34 -). The following code shows how the region from the coordinates (0, 0) through to (99,99) can be copied to the coordinate (100, 100).
¨§

fits_image copy_buf;fits.image("Primary").copy(&copy_buf, 0, 100, 0, 100);
fits.image("Primary").paste(copy_buf, 100, 100);¥¦

The object fits_image created by the programmer (=copy_buf) becomes the copy buffer. The
Copy and Paste will be carried out by the member function applied to the object copy_buf. The
number of objects is unlimited. Copying and pasting between objects is easy.
Rather than paste() the functions of add(), subtract(), multiply(), and divide() provide
for the addition, subtraction, multiplication, and division operations (between objects), respectively (§12.6.29 -).
The object copy_buf used as the copy buffer stated in the above example can be applied in all
the member functions in §12.6. For example, copy_buf can read, write, and edit values as follows.

56

SFITSIO User’s Reference Guide¨¥

v = copy_buf.dvalue(x0,y0);
copy_buf.assign(v,x1,y1);§¦

The object copy_buf acts as an image HDU that is independent of the fits object (the FITSCC
class object).
The object copy_buf can be saved in a FITS file. With the case below programmers create
a new FITSCC class object, register the content of the object copy_buf, and then save the new
object in a file.
¨

fitscc new_fits;
new_fits.append_image("Primary",0, FITS::DOUBLE_T,0);
new_fits.image("Primary").swap(copy_buf);
new_fits.write_stream("copy_buffer.fits");

§

¥

¦

This program creates a primary HDU without any image data in a new object new_fits(the primary HDU is created using new_fits.image("Primary") unless it already exists) andexchanges the content with that of copy_buf. Although new_fits.append_image(copy_buf);
can be used instead of the member function swap(), new_fits.append_image(copy_buf) requires
twice the memory that swap() does and therefore the recommendation is not to use it with large
amounts of image data.

5.11

Type conversion and fast access to image data

Fast access to the internal data of an object using pointer variables is supported. Note that theaddresses of the data array will change when the size of pixels is changed using member functions
such as image().resize() (§12.6.22).
To ensure fast access it is recommended to have internal data converted beforehand in order toavoid any conversions using the values of BZERO and BSCALE when reading data. For conversions
use the member function image().convert_type() (§12.6.13).
¨¥fits.image("Primary").convert_type(FITS::DOUBLE_T);§¦

In this way any type of data can be converted to type double in which BZERO and BSCALE
equal 0 and 1. In addition, the address of the data can be obtained using the member function
image().double_t_ptr(), image().float_t_ptr(), etc. (§12.7.2) for each of the internal datatypes.
¨

fits::double_t *ptr:
ptr = fits.image("Primary").double_t_ptr();§¥¦

You can now access the internal data using “ptr[x + y * col_length]”.

5.12

Collaborations with libwcs of WCSTools

WCSTools27) is a C library for use in the efficient handling of astronomical data. It can be used
for processing within the WCS(World Coordinate System), accessing FITS files, and searchingimportant star catalogs. Mr. Douglas J. Mink at SAO is responsible for the development of thislibrary.
Here, we will provide an an example and explain how you can easily handle WCS using SFITSIO
and libwcs.
First, you have to write the include declarations.
27)

http://tdc-www.harvard.edu/wcstools/

Ver. 1.2.1

57¨#include <sli/fitscc.h>#include <math.h>#include <libwcs/wcs.h>using namespace sli;§¥¦

Next, we will show the main() function. First, the FITS file ‘foo.fits.gz’ is read, and an
object of the WorldCoor structure created, which is pointed by the wcs pointer variable, fromthe FITS header of the Primary HDU. In this step the header formatted string() member
function of SFITSIO is useful in that it can be used to obtain a string which contains all theheader records of an HDU(See §12.4.35). The next step involves the WCS conversion: the function
pix2wcs() converts pixel coordinates to celestial coordinates, whereas the function wcs2pix()
converts celestial coordinates to pixel coordinates. The last piece of code frees up the memory
used by wcs.
¨
int main( int argc, char *argv[] ){fitscc fits;
struct WorldCoor *wcs;
double lon,lat, x,y, v;
int off;¥/* FITS object *//* WCS structure *//* read all data from fits file */fits.read_stream("foo.fits.gz");/* create alias ‘pri’ to Primary HDU */fits_image &pri = fits.image("Primary");/* initialize wcs structure */wcs = wcsinitn(pri.header_formatted_string(), NULL);/* convert pix -> wcs */x = 1.0; y = 1.0;
pix2wcs(wcs, x, y, &lon, &lat);
printf("ra=%.8f dec=%.8f\n",lon,lat);/* convert wcs -> pix */wcs2pix(wcs, lon, lat, &x, &y, &off);
printf("x=%.8f y=%.8f\n",x,y);/* read value of pixel (1-indexed) */v = pri.dvalue((long)floor(x-0.5),(long)floor(y-0.5));
printf("value=%.15g\n",v);/* free wcs structure */wcsfree(wcs);
return 0;}§¦

With your actual code the validity of the WorldCoor object should be checked using iswcs().
The function iswcs() returns 1 or 0, which respectively indicate whether the object is valid orinvalid.
If you want to know more about libwcs read the header files of WCSTools package, e.g., wcs.h,
etc. The header files of WCSTools sufficiently explain the use of powerful APIs, and users cantherefore only use these APIs after having read them.
See also sample_wcs/wcs_test.cc in the SFITSIO source package.

58

SFITSIO User’s Reference Guide

5.13

Collaborations with WCSLIBWCSLIB28) is a library that was developed by Ph. D. Mark Calabretta to use in manipulating
the World Coordinate System (WCS). The combination of SFITSIO with WCSLIB makes it easy
to manipulate WCS. This subsection provides a simple example of SFITSIO being combined withWCSLIB. The example program obtains specific celestial coordinates that correspond to pixels
included in a FITS file (read to the object in_fits) with a WCS header. In addition, the program
also obtains the value of the pixels in a new FITS file (in the object out_fits) with a WCS header.
First, you have to include header files like this:¨#include <sli/fitscc.h>#include <sli/tstring.h>#include <wcshdr.h>§#include <wcs.h>¥¦Create an object out_fits for output to a file that is described as below using a function, suchas main.
¨

fitscc out_fits;
struct *wcs_out;
tstring headerall;
int status=0, nrecords, relax=1, nreject, nwcs, ctrl=0, anynul;
out_fits.append_image("Primary",0,
FITS::FLOAT_T,1024,1024); /* 1024x1024 FLOAT image */fits_image &outfitspri = outfits.image("Primary");
outfitspri.header("RADESYS").assign("FK5").assign_comment("Coordinate System");
outfitspri.header("EQUINOX").assign(2000.0).assign_comment("Equinox");outfitspri.header("CTYPE1").assign("RA---TAN"); /* Tangential projection */outfitspri.header("CTYPE2").assign("DEC--TAN"); /* Tangential projection *//* Pixel coordination of the reference point */outfitspri.header("CRPIX1").assign(512.5);/* Pixel coordination of the reference point */outfitspri.header("CRPIX2").assign(512.5);/* Right ascension (RA) of the reference point */outfitspri.header("CRVAL1").assign(0.0);/* Declination (D) of the reference point */outfitspri.header("CRVAL2").assign(0.0);/* Increment of the coordinate (RA is increased in the right direction) */outfitspri.header("CDELT1").assign(-0.01);/* Increment of the coordinate (D is increased in the upward direction) */outfitspri.header("CDELT2").assign(0.01);
headerall = outfitspri.header_formatted_string();
nrecords = headerall.length()/80;
wcspih((char*)headerall.cstr(), nrecords, relax, ctrl, &nreject, &nwcs, &wcs_out);
wcsprt(wcs_out);

§

¥

¦

Here we create an output file, define a WCS header, and import values into the structure
wcs_out. The function wcspih() loads a WCS header into the structure(s). The function requires
one string that is composed of all the headers related to WCS in the first argument. The string
should be a byte image in a FITS file, but the member function header_formatted_string()(§12.4.35) obtains the byte image of the header as an object of the class tstring (the tstring classis described in APPENDIX3 (§15)). The program then displays the content of the structure(s)using wcsprt() at the end.
In the same manner the program loads the WCS header in the object in_fits into the structure
wcs_in.
28)

http://www.atnf.csiro.au/people/mcalabre/WCS/WCSLIB

Ver. 1.2.1
¨

§

59

fitscc in_fits;
struct wcsprm *wcs_in;
in_fits.read_stream("user_image_file.fits");headerall = in_fits.image("Primary").header_formatted_string();
nrecords = headerall.length()/80;
wcspih((char*)headerall.cstr(), nrecords, relax, ctrl, &nreject, &nwcs, &wcs_in);
wcsprt(wcs_in);¥¦

This code obtains celestial coordinates (world[0][0], world[0][1]) corresponding to specificpixel coordinates (x out, y out) in the object in_fits, calculates where the obtained coordinatescorrespond to the pixel coordinates in the object out_fits, and then substitutes the calculated
coordinates into (pixcrc in[0][0], pixcrc in[0][1]).

¨

§

¥

double pixcrd_in[1][2], pixcrd_out[1][2], imgcrd[1][2];double phi[1], theta[1], world[1][2];double x_out, y_out, x_in, y_in;
pixcrd_out[0][0] = (double)x_out;
pixcrd_out[0][1] = (double)y_out;
wcsp2s(wcs_out, 1, 2, pixcrd_out[0], imgcrd[0], phi, theta, world[0], &status);
wcss2p(wcs_in, 1, 2, world[0], phi, theta, imgcrd[0], pixcrd_in[0], &status);
x_in = (float)pixcrd_in[0][0];y_in = (float)pixcrd_in[0][1];¦The function wcsp2s() transforms the pixel coordinates to the world coordinates while thefunction wcss2p() the world coordinates to pixel coordinates. The functions wcspih(), wcsprt(),wcsp2s(), and wcss2p()Äwere used in the program described above. Knowledge of these functions
enables you to do WCS related calculations. In addition, wcsset() and wcs_errmsg() are also
useful functions. The former can be used to reset the structure wcsset(wcs_out) while the lattercan be used to obtain the string of error messages as wcs_errmsg[status].

5.14

Accessing ASCII and binary tables

The same member functions in SFITSIO manipulate both ASCII and binary tables.
First of all, we will show you how to check the size of the table. It can be obtained using themember functions table().row_length() (§12.8.4) and table().col_length() (§12.8.3). The
following provides an example of how to display the size of binary table the “EVENT”.
¨§¥

printf("Num. of Columns : %ld\n",fits.table("EVENT").col_length());
printf("Num. of Rows
: %ld\n",fits.table("EVENT").row_length());¦

You can access table data in the similar style to accessing FITS headers, such as fits.table(HDU
name).col(column name). .... If the HDU or column does not have a name an index number
beginning with 0 can be specified.
Each of dvalue(), lvalue(), llvalue(), bvalue(), and svalue can be used to read the value,
and assign() to write it (§12.8.20 -). These functions also automatically convert the values using
the values TZEROn and TSCALn in the header.
The function dvalue() can be used to read the columns of any type of data as type double.
The row number starts with 0. The following provides an example of how to read/write values of
the column “TIME” in the binary table “EVENT”.
¨§

double val;
val = fits.table("EVENT").col("TIME").dvalue(row_index0);
fits.table("EVENT").col("TIME").assign(val,row_index1);¥/* Read *//* Write */¦As shown in the example the index of the row is specified when read and the value and index
in this order when written in the arguments.

60

SFITSIO User’s Reference Guide

You can read and write both integer and Boolean values. The functions lvalue(), llvalue(),and bvalue() return values of the long, long long, and Boolean type, respectively. To read string
type values use svalue(). The function svalue() converts values into a string, which is formatted
according to what is specified by TDISPn in the header if the value is a number.
¨§const char *sval;
sval = fits.table("EVENT").col("TIME").svalue(row_index0);
printf("%s\n",sval);¥/* Read *//* To stdout */¦A column can have multiple elements; for example TFORMn = ’8J’ means that the column has
eight elements. The number of the elements can be obtained using table(...).col(...).elem_length()(§12.8.13). The element to be read from the column can be specified using the second argument ofeach of dvalue(), lvalue(), llvalue(), bvalue(), and svalue(). When written, the same canbe specified using the third argument of assign(). The following code is an example of how todisplay all the elements of the column “STATUS” and for every row.
¨

§

5.15

long i, j, nrow, nel;const char *sval;
nrow = fits.table("EVENT").row_length();/* Number of rows */nel = fits.table("EVENT").col("STATUS").elem_length();/* Number of elements */for ( i=0 ; i < nrow ; i++ ) {for ( j=0 ; j < nel ; j++ ) {sval = fits.table("EVENT").col("STATUS").svalue(i,j);printf("%s ",sval);}printf("\n");}¥¦Creating binary tables

The following example shows the case of creating a binary table for data from the astronomy
satellite of ASTRO-X. Sample code, create_bintable.cc, which can be compiled, is available inthe directory sample of the distribution package.
It creates a table composed of the three columns of (double, 32-bit integer, and string).
¨§

fitscc fits;
const fits::table_def def[] = {/* ttype,comment,talas,telem,tunit,comment,*//*
tdisp, tform, tdim*/
{ "TIME","satellite time","", "", "s","", "F16.3", "1D", "" },{ "STATUS","status","", "", "","", "","8J", "" },{ "NAME","","", "", "","", "", "128A16", "(4,2)" },{ NULL }};/* Create a binary table (name of HDU is "EVENT") */fits.append_table("EVENT",0, def);¥¦

First, it prepares for defining the columns with structures, and then creates a binary tableusing the member function append_table() (§12.3.17). Binary tables cannot be primary HDUs
with FITS definitions, and hence a primary HDU without any image data is automatically created.
Second, the rows of the table can be allocated as follows.
¨§¥

fits.table("EVENT").resize_rows(256);¦

Ver. 1.2.1

5.16

61

Creating ASCII tables

The method used to create ASCII tables is similar to that with binary tables. However, care should
be taken when you specify tdisp and tform in the structure. When creating ASCII tables thestrings to be written in TFORMn of the FITS file are specified by tdisp in the structure, and thewidth of the strings by tform in the structure in the form of "nA".
It creates a table composed of three columns.
¨

fitscc fits;
const fits::table_def def[] = {/* ttype,comment,talas,telem, tunit,comment, tdisp, tform */{ "PK","PK number","","", "","","A9","9A" },{ "RAH","Hours RA","","", "h","","I2","3A" },{ "RAM","Minutes RA","","", "min","","F5.2", "6A" },{ NULL }};/* Create an ASCII table (name of HDU is "PLN") */fits.append_table("PLN",0, def, true);

§

¥

¦

First, prepare the definition of columns with structures, and then create an ASCII table using
the member function append_table() (§12.3.17) and true as the final argument. ASCII tables
cannot be primary HDUs with FITS definitions, and hence a primary HDU without any image
data is automatically created.
Second, the rows of the table can be allocated as follows.
¨¥

fits.table("PLN").resize_rows(256);§¦

See also sample/create_asciitable.cc in the SFITSIO source package.

5.17

Editing and importing ASCII and binary tables

SFITSIO enables not only the addition, insertion, and deletion of columns (§12.8.46 -) and rows(§12.8.52 ) but also the other ASCII tables or binary tables to be imported (§12.8.58).
The following code is an example of how to copy the as-is content of the column “DEC” in one
FITS table to another.
¨
§
¨

§

¥

fits_out.table("EVENT").append_a_col( fits_in.table("SRC").col("DEC") );The next example shows how to combine the two tables.
long orow_length = fits_out.table("EVENT").row_length();fits_out.table("EVENT").resize_rows( orow_length + fits_in.table("SRC").row_length() );fits_out.table("EVENT").import_rows( orow_length, true, fits_in.table("SRC") );¦¥¦First, the member function resize_rows() increases the number of rows up to the sum of thetwo tables. Last, the member function import_rows() (§12.8.58) pastes the entire content of thetable SRC to the rear margin of the table EVENT. The arguments passed to import_rows() provide
the number of rows where the paste operation will begin, whether it pastes the column to which
the name matches, and the source of the table.
Member function table().col().import() (§12.8.62) can be used to import units of a column.

62

SFITSIO User’s Reference Guide

5.18

Editing of HDU

It is easy to merge the images of multiple FITS files and ASCII or binary tables into one FITS andthen delete the unnecessary HDUs using SFITSIO. Providing fits.image("FOO") or fits.table("BAR")
as the argument of member functions .append_image(), .append_table() and so on provides foreasy additions (§12.3.16, §12.3.17) and insertions (§12.3.18, §12.3.19) of Image HDUs and binary(or ASCII) table HDUs.
The following code is an example of adding an as-is table EVENT in the object fits_in to theobject fits_out.
¨
§
¨
§

¥

fits_out.append_table( fits_in.table("EVENT") );The next example involves the deletion of the HDU name FOO of an object fits_out.
fits_out.erase("FOO");¦¥¦

Ver. 1.2.1

6

63

Things to know before using SFITSIO

You will be using a C++ compiler because SFITSIO is a C++ library. C++ is upwardly compatible
with C, and hence basically you can write code in the same style as C.
However, there are a few (but not very difficult) things you need to know before using SFITSIO.
Incompatibilities between C and C++ accompanied by the extensions of C++ do exist but whicheasily and conveniently extend the functionality of C++. We will describe them in this section.

6.1

NamespaceNamespace is one of the things that was introduced in C++. It is used to avoid the problem ofdifferent programmers writing the same name of functions or types. It is similar to a categoryname. SLLIB and SFITSIO assign their own namespace as “sli”. If you use some kind of class you
will need to put sli:: at the top, for example “sli::stdstreamio sio;”, in order for the code
to be written in the proper form.
If you will be mainly using SFITSIO you may not want to have to write sli:: every time. In
this case follow the style below to skip having to use sli:: throughout the rest of the code.
¨

¥

§

¦

using namespace sli;

The examples in this manual omit sli::. For C++ beginners it may be easier to keep in mind
that once you have written “#include <...>” then you should write “using namespace sli;”.

6.2

NULL and 0With many processing systems NULL with C is defined as
define NULL ((void*)0)
But NULL with C++ is defined as
define NULL (0).
The reason why NULL is 0 in C++ is that the check of the type of pointer variables with C++ isstricter than that with C. For instance, suppose that there are two pointer variables, char *ptr0;
void *ptr1; and then an error occurs when you try to substitute ptr0 with ptr1. Zero (0) is
defined as a “nowhere address” so that ptr0 = 0; does not generate an error. This is exactly why
NULL is 0 with C++.
With C++ a member function of a class may have the same name but different arguments.
For example,
int foo( int a );int foo( char *p );If both hoge.foo(NULL) or hoge.foo(0) exist the compiler will not be able to determine whichfunction should be used. In this case it is necessary to explicitly indicate the type. That is¨§¥

hoge.foo((char *)NULL);
hoge.foo((int)0);With C++ it is safer to remember that “cast if use NULL or 0”. Another way is to cast NULL
out and “always cast 0”.

6.3

Reference

It is too much work to write fits.hdu("Primary") or fits.image("Primary") with every accessto the header or the image. “Reference” therefore makes this shorter. Reference, also called¦

64

SFITSIO User’s Reference Guide“Alias”, creates an alias of a variable or an object but in simple terms. Although Macro may be
used for aliases for variables or objects use of references allows for smarter scripting.
The reference introduced in C++ is a new type that is similar to the pointer type. In fact, thefunctions of the reference are simpler than that of the pointer type. Accordingly, its
usage is simple too. For example, creating the reference “aref” of the variable int a; involves¨§

int &aref = a;¥¦

A reference, or so called “Alias”, acts exactly the same way. For instance,
aref = 10;
then, 10 is assigned to a, andint b = aref;
substitutes the value of b with a.
int *p = &aref;
substitutes p with the address of a.
As described above reference is a simple way of providing an alias for a variable. It is not
as complicated as pointer variables with their many *. Reference cannot have NULL because it is
impossible to create any references without their actual existence.
When using SFITSIO you can mostly use a reference to copy it after returning from a member
function to another reference variable that the user creates. For instance, the member function
fits.hdu() returns a reference to “fits_hdu &”. If a user creates a reference of the same class andcopies the return value in the receipt side it can then be a substitution for fits.hdu("Primary")or fits.image("Primary"), thus allowing the user to write less code. The following code provides
an example.
¨§¥

fits_hdu &primary = fits.hdu("Primary");
printf("TELESCOP = %s\n",primary.header("TELESCOP").svalue());¦

In other words,¨§¥

fits_image &primary = fits.image("Primary");
printf("TELESCOP = %s\n",primary.header("TELESCOP").svalue());¦

Please note that using a reference without substituting the value in the declaration will result inan error. This is because “Alias” means “another name”. An “Alias” being used without actuallyexisting results in an error.

6.4

Try & catch

You can skip this part unless you intend to write rather heavy code.
The syntax try{} and catch(){} are used to deal with the “Exception” introduced in C++.
SFITSIO results in an “Exception” when a critical problem, such as “memory allocation failed”,
occurs with arguments provided by users. An “Exception” can be handled using try{} andcatch(){} in the user’s code. With SFITSIO any exceptions that have occurred always resultin a message of the err_rec type. Deal with it by writing

Ver. 1.2.1
¨

§

65
¥

try {
/* Change the buffer size of image */fits.image("Primary").resize(0,very_big_size);
return_status = 0;}
catch ( err_rec msg ) {fprintf(stderr,"[EXCEPTION] function=[%s::%s] message=[%s]\n",msg.class_name, msg.func_name, msg.message);
return_status = -1;}¦

If an exception occurs without use of try{} and catch ( err_rec msg ){} the functionabort() will be called and the program will terminate.
Generally, any such critical error in most cases will abort the program. If you do not haveany problem with using the program called abort() it will not be necessary to use try{} andcatch( err_rec msg ){}.

66

SFITSIO User’s Reference Guide

7

Tips on appropriately handling FITS with SFITSIO

7.1

Policies with coding in accordance with the memory management schemeof SFITSIO and hardware selection

The classes provided by SFITSIO and SLLIB have a very simple structure with no internal reference
counter29) and always one (set of) internal buffer(s) per object. This then means that the memoryarea required for an assignment operation is immediately allocated upon assignment to a new
object using the init() member function or the “=” operator.
Memory mapping is also very simple, with both the image buffer for the fits image class andthe column data buffer for the fits table col class always being allocated as one-dimensional
arrays.
Programmers can therefore write code using the address of the internal buffer within an object
in much the same way as a memory area with the C language (any such handling should be limited
to cases where a greater level of performance is required, though). However, it entails significant
overhead with the execution of operations such as having to remove the middle part of the data andmoving the data that follows forward in thereby filling in the gap, or inserting data in the middleof the buffer, and even if they are operated within the memory. Any such operations should be
reduced as much as possible by writing the proper code and selecting the proper member functionsin thereby ensuring good performance.
Next, hardware. It goes without saying that an adequate amount of memory is required for thesize of FITS files that the application will be handling via use of SFITSIO. I would recommend
installing additional memory in thereby ensuring an average amount of free memory space thatmatches the largest size FITS files to be handled by the application.
SFITSIO also adopts the simple policy of re-allocating memory where the responsibility is left
to the OS and programmers; it always calls realloc() internally if it identifies resize() that themember function etc. requires a change in the size of the buffer. It is up to programmers whether
to reduce the frequency of realloc() calls by consistently having enough of a buffer size or to
pursue memory saving by allowing more calls to realloc().
In addition, there is no member function that returns the address of a dynamically createdobject with SFITSIO or SLLIB. This therefore makes delete or garbage collector unnecessary
except for objects dynamically created by programmers.

7.2

Tricks for faster operation

Tricks for faster operation often depend on the computing architecture used. Furthermore, andbecause computing architecture changes over time, the quest for faster operations typically remains
a perpetual challenge30) . Moreover, any excessive pursuit of faster operation could harm thereadability and safety of the code. Any performance tuning should therefore only be carried out
in view of the forecast future computing architecture and be in proper proportions with otherevaluation axes.
That said, the basics for faster operation will remain unchanged, and include reducing the total
number of steps in the eventual code of the machine language. I will cover some of what programmers can do to fulfill that purpose while referring to the internal implementation of SFITSIO.
• Although great care has been taken in accessing objects by name, it still involves relatively
large overhead.
29)

There is no static member function, either.
An extreme example would involve the technique of rewriting the machine code of the program itself, dependingon the conditions, and in order to avoid any conditional branches in the loop. Any such code would become inoperable
if the CPU utilized cache memory.
30)

Ver. 1.2.1

67

As shown in Question 1 of §1.1 SFITSIO enables you to access the header or a columnof the table by name. Because both the header and the table are internally represented bysimple object arrays with SFITSIO it has to quickly convert the names into indices in thereby
maintaining the level of performance.
SFITSIO creatively utilizes the ctindex class of SLLIB, and which enables fast searches byrepresenting the relationship between the key string and the index as a tree structure (formore details refer to the SLLIB advanced user reference guide).
However, all the effort put into using that algorithm still involves a large amount of overhead
when compared to direct indexing. creativity on the part of programmers is therefore stillrequired; in order to achieve a higher level of performance programmers must use directindexing after converting from the name to the index only once, as well as writing code thatutilizes references.
• Using inline member functions and member functions that utilize macro expansion
Member functions that process images (§4.7.16) utilize macro expansion in order to minimize
conditional branches within for() loops and ensure faster operation.
With the current version of SFITSIO the functions that return sizes such as the numberof pixels and the ultra-low level API functions are inline member functions. Inline member
functions will be even more widely used in future versions of SFITSIO. Please therefore
ensure to check the content of the header files whenever a new version is released.
• Reducing the frequency of calls to member functions
The overhead involved with calling member functions may cause problems, for example,
inside multiply nested loops. In the case of SFITSIO they are implemented with efficiency inmind, for example by using them inline, but there is still much room for improvement. Even
faster operation can be expected in the future.
Better performance can also be effectively achieved by reduce the frequency of member
function calls on the part of programmers. Creative use of references, as shown in the next
example, can achieve this.
¨¥const fits_table &tbl = fits.table("FOO");
const fits_table_col &col = tbl.col("BAR");for ( j=0 ; j < tbl.row_length() ; j++ ) {printf("[%s]", col.svalue(j));
}
§

¦

68

SFITSIO User’s Reference Guide

8

Template Files‘Template File’ is a text file written with lenient syntax similar to FITS header, and defines aformat of new FITS files. SFITSIO can read template files, and creates fitscc objects and FITS
files having no data contents. Template files are generally used to manage various FITS formats.

8.1

Creating Image HDUThis template file creates a Primary HDU:
¨

¥

§

¦

#
# Test for Primary only#
NAXIS2 = 16
NAXIS1 = 16
BITPIX = 32
FMTTYPE = ASTRO-X xxx image format
CHECKSUM =DATASUM =COMMENT ---------------------------------------------------------------EQUINOX = 2000.0
CTYPE1 = RA---TANCTYPE2 = DEC--TANCRPIX1 = 0.0
CRPIX2 = 0.0
CRVAL1 = 0.0
CRVAL2 = 0.0
CDELT1 = 0.1
CDELT2 = 0.1
PC1_1
= 1.0
PC1_2
= 0.0
PC2_1
= 0.0
PC2_2
= 1.0
COMMENT ---------------------------------------------------------------MESSAGE = ’FITS (Flexible Image Transport System) format is &’ / In SFITSIO,CONTINUE ’defined in "Astronomy and Astrophysics", volume 376, &’ / this
CONTINUE ’page 359; bibcode: 2001A&A...376..359H’ / message is not written &CONTINUE automatically.

In template files, users do not have to fix column positions of keyword, “=”31) , value, and comment.
In addition, there is no limit of length of text column, and long string values can be written withor without CONTINUE keywords. Lines whose first character is “#” are ignored by the SFITSIO
build-in parser.
Next, we show the FITS header created from above template file.

31)

In CFITSIO, “=” can be omitted. However, SFITSIO does not permit such an omission.

Ver. 1.2.1¨

69¥

SIMPLE =T / conformity to FITS standard
BITPIX =32 / number of bits per data pixel
NAXIS=
2 / number of data axes
NAXIS1 =16 / length of data axis 1
NAXIS2 =16 / length of data axis 2
EXTEND =F / possibility of presence of extensions
FMTTYPE = ’ASTRO-X xxx image format’ / type of format in FITS file
FTYPEVER=
0 / version of FMTTYPE definition
CHECKSUM= ’ZlBRfj9OZjAOdj9O’/ HDU checksum : 2012-01-17T06:07:12
DATASUM = ’0’
/ data unit checksum : 2012-01-17T06:07:12
COMMENT ---------------------------------------------------------------EQUINOX =2000.0 / equinox of celestial coordinate system
CTYPE1 = ’RA---TAN’/ type of celestial system and projection system
CTYPE2 = ’DEC--TAN’/ type of celestial system and projection system
CRPIX1 =0.0 / pixel coordinate at reference point
CRPIX2 =0.0 / pixel coordinate at reference point
CRVAL1 =0.0 / world coordinate at reference point
CRVAL2 =0.0 / world coordinate at reference point
CDELT1 =0.1 / world coordinate increment at reference point
CDELT2 =0.1 / world coordinate increment at reference point
PC1_1=
1.0 / matrix of rotation (1,1)
PC1_2=
0.0 / matrix of rotation (1,2)
PC2_1=
0.0 / matrix of rotation (2,1)
PC2_2=
1.0 / matrix of rotation (2,2)
COMMENT ---------------------------------------------------------------MESSAGE = ’FITS (Flexible Image Transport System) format is defined in &’CONTINUE ’"Astronomy and Astrophysics", volume 376, page 359; bibcode: &’CONTINUE ’2001A&A...376..359H&’CONTINUE ’’ / In SFITSIO, this message is not written automatically.
§END¦
Template files minimize items that users have to write for definitions of FITS files. For example,
SIMPLE, EXTEND, NAXIS, and comments for general FITS keywords are omitted in above template
file. However, SFITSIO automatically completes required keywords and comments, and adjusts
the order of keywords so that created FITS header satisfies FITS standard.

8.2

Creating Binary Table HDU

Next, we show a template file to create a FITS file including a binary table HDU.

70

SFITSIO User’s Reference Guide¨## Primary#
FMTTYPE = ’ASTRO-X XXXX table format’
FTYPEVER = 101
EXTNAME = ’Primary’
ORIGIN= ’JAXA’## 2nd HDU : Binary Table#XTENSION = BINTABLE
NAXIS2 = 24
PCOUNT = 65536
THEAP = 32768
EXTNAME = XXXX_TEST
TXFLDKWD = ’TNOTE,TDESC,TLMIN,TLMAX,TDMIN,TDMAX’TTYPE# = TIMETALAS# = DATETFORM# = 1D
TDESC# = ’This is time’ / description of this field
TTYPE# = COUNTERTFORM# = 8J
TLMIN# = 1
TLMAX# = 16777216
TDMIN# = 0
TDMAX# = 0
TTYPE# = XNAMETFORM# = 16A
TTYPE# = VLATFORM# = 1PJ(0)TNOTE# = ’You can define variable length array in SFITSIO template&’
CONTINUE ’’ / annotation of this field§¥¦

Descriptions for Primary HDU can be omitted completely. If you want to define some header
records in Primary HDU, you can define them before definitions of binary table HDU like thisexample.
In the definition of second HDU, XTENSION keyword must be written first, and BITPIX, NAXIS,NAXIS1, NAXIS2, PCOUNT, GCOUNT, TFIELDS can be omitted. Note that TXFLDKWD keyword in thisexample is used to indicate non FITS standard keywords of table columns (fields) such as TLMINn,
TLMAXn, etc. FITS libraries can know newly defined column keywords by reading TXFLDKWD record.
See also §10.7 for TXFLDKWD convention.
Automatic numbering is available for column definitions such as TTYPEn keywords.. Whenusing this feature, “#” symbol is written after column keywords in template files like TTYPE# inabove example. However, note that following case does not give what you want.
¨

TTYPE#TTYPE#
TFORM#§ TFORM#= TIME= COUNTER
= 1D
= 8J

We show FITS header created from the template file.

¥¦Ver. 1.2.1¨

71¥

SIMPLE =T / conformity to FITS standard
BITPIX =16 / number of bits per data pixel
NAXIS=
0 / number of data axes
EXTEND =T / possibility of presence of extensions
FMTTYPE = ’ASTRO-X XXXX table format’ / type of format in FITS file
FTYPEVER=
101 / version of FMTTYPE definition
EXTNAME = ’Primary ’/ name of this HDU
ORIGIN = ’JAXA’/ organization responsible for the data
§END
¨

¦
¥

XTENSION= ’BINTABLE’/ type of extension
BITPIX =8 / number of bits per data element
NAXIS=
2 / number of data axes
NAXIS1 =64 / width of table in bytes
NAXIS2 =24 / number of rows in table
PCOUNT =65536 / length of reserved area and heap
GCOUNT =1 / number of groups
TFIELDS =4 / number of fields in each row
THEAP=32768 / byte offset to heap area
EXTNAME = ’XXXX_TEST’/ name of this HDU
TXFLDKWD= ’TALAS,TDESC,TNOTE,TLMIN,TLMAX,TDMIN,TDMAX’ / extended field keywords
TTYPE1 = ’TIME’/ field nameTALAS1 = ’DATE’/ aliases of field name
TFORM1 = ’1D’/ data format : 8-byte REALTDESC1 = ’This is time’/ description of this field
TTYPE2 = ’COUNTER ’/ field name
TFORM2 = ’8J’/ data format : 4-byte INTEGERTLMIN2 =1 / minimum value legally allowed
TLMAX2 =16777216 / maximum value legally allowed
TDMIN2 =0 / minimum data value
TDMAX2 =0 / maximum data value
TTYPE3 = ’XNAME’/ field name
TFORM3 = ’16A’
/ data format : STRING
TTYPE4 = ’VLA’
/ field name
TFORM4 = ’1PJ(0) ’/ data format : variable length of 4-byte INTEGER
TNOTE4 = ’You can define variable length array in SFITSIO template&’
CONTINUE ’’ / annotation of this field
§END
¦

8.3

Specification of SFITSIO template

1. Template files are written with plain text format having UNIX or DOS newline.
2. Lines whose first character is “#” are ignored by SFITSIO parser.
3. A tab character is simply replaced with a white space.
4. Order of keyword, “=”, value, “/”, and comment must be the same as that of FITS header,
however, there is no rule for position of keyword, etc. Note that record with ‘8-space keyword’
will be created for the line beginning space or tab whose length is 8 or more.
5. There is no limit of length of columns in template files.
6. In template, long string values can be written in a line. Using CONTINUE keyword is also
permitted. However, the position of “&” character for CONTINUE convention will not bepreserved in FITS header.

72

SFITSIO User’s Reference Guide
7. Quotations for a string value can be omitted only if the value cannot be interpreted as
numeric or logical value. However, quotations should not be omitted when using CONTINUE
convention.
8. When a very long description using COMMENT is written in template, multiple COMMENT records
will be created to store the long description.
9. First keyword must be XTENSION for second or later HDUs.

10. The order of keywords in template is not prescribed except XTENSION and keywords for table
columns (fields).
11. The order of keywords in template is reflected in FITS header, when it does not break FITS
standard.
12. SIMPLE, NAXIS, EXTEND, PCOUNT, and GCOUNT keywords can be omitted in Image HDU.
13. BITPIX, NAXIS, NAXIS2, PCOUNT, GCOUNT, and TFIELDS keywords can be omitted for Binary
Table HDU or ASCII Table HDU. NAXIS1 is also not required for Binary Table.
14. Automatic numbering is applied for keywords with “#” suffix of table columns such as TTYPE#.
Counter increment for this numbering is done when parser detects first keyword having “#”
suffix in the HDU definition.
15. When comments after “/” character are omitted in template, SFITSIO completes the comment using built-in default comments when the record has FITS standard keywords. Blank
comments for non FITS standard keywords are also filled for well known keywords.32)
16. “=” cannot be omitted when creating records of ‘keyword = value / comment’ .
17. Keywords of template are case insensitive in current version of SFITSIO, however, we recommend users to write uppercase keywords.

32)

See APPENDIX2 (§14) for details.

Ver. 1.2.1

73

9Local FITS Extension Compatible with CFITSIO

9.1

Long header value across multiple records

In SFITSIO, as well as in the CFITSIO, in case that a header string cannot be fitted into 1 line of
the header record, save by using CONTINUE as follows.
¨

TELEM6 = ’CREON,SHTOP,FWPOSON,FWPOS_B1,FWPOS_B0,MPOSON,MPOS_B1,MPOS_B0,&’
CONTINUE ’RSTWIDELON,RSTWIDESON,RSTN170ON,RSTN60ON,LWBOOSTON,SWBOOSTON,&’CONTINUE ’LWBIASON,SWBIASON,CALALON,CALASON,CALBON,SINALON,SINASON&’CONTINUE ’’ / elements in STATUS§¥¦

In case of SFITSIO, this process for extension, i.e., data conversion between a file and an
object is carried out at file I/O. Since there are no restriction of string length for the object of the
SFITSIO, an API specialized for long value as in the CFITSIO does not exist. That is, users don’t
need to mind whether there is the CONTINUE record or not on the file.

9.2

Array of fixed length strings in binary table

In CFITSIO, assignments such as TFORMn = ’120A10’ or, TFORMn = ’120A’ AND TDIMn = ’(10,12)’
allows users to treat 12 sets of 10-character string in a column. The SFITSIO also supports these
Extension of FITS.
Furthermore, in the SFITSIO, an assignment like TFORMn = ’120A10’ AND TDIMn = ’(6,2)’
allows users to treat a 10-character string as a 6 × 2 array. This assignment can also be written as
TFORMn = ’120A’ AND TDIMn = ’(10,6,2)’.

9.3

Writing checksum and datasum

If each header of HDU has CHECKSUM or DATASUM keyword, SFITSIO automatically writes the
CFITSIO-compatible checksum or datasum when saving FITS files. Here is an example:¨

CHECKSUM= ’LNXALNX2LNX8LNX8’DATASUM = ’2155872383’§¥/ HDU checksum : 2012-01-16T13:34:03/ data unit checksum : 2012-01-16T13:34:03¦

Note that the values of CHECKSUM and DATASUM are basically calculated by only summing up 32bit integers with treating all byte data in an HDU as binary data that consist of 32-bit integers.
Therefore, they will not enough to certify an identity of data. We recommend you to use md5sum
for such a purpose.
SFITSIO of current version has no function to test the values of CHECKSUM and DATASUM records.

74

SFITSIO User’s Reference Guide

10

SFITSIO’s Original Extension of FITS

In this section, we mainly explain extension about binary table. The extensions from §10.8 havebeen defined in ‘AKARI’ project of ISAS/JAXA to store complicated data into FITS binary tablewith better readability and to process them efficiently. The AKARI team have discussed these
extensions for a long term software development.

10.1

Error Check and Version Management of FITS File by FMTTYPE andFTYPEVER

Shown in §1.2, the ‘AKARI’ project team defined the TSD format, and discussed how to manage
version of TSD or detect errors while loading FITS files in programs developed in the project.
As a result, the project team defined FMTTYPE and FTYPEVER keywords in the primary header
to indicate “What is this FITS file?” and version of structure in a FITS file, respectively. For
the value of keyword FMTTYPE, a string which defines globally unique data format, i.e., such as“Project Name, Equipment Name, File Type”, should be set. The FTYPEVER should be set an
integer version number.
We recommend using more than three digit number for FTYPEVER to express a minor version.
Alternatively, a date such as 20080101 can also be used.
SFITSIO supports FMTTYPE and FTYPEVER keywords in dedicated member functions.

10.2

Distinction of upper and lower case in the header keyword

Current FITS standard does not permit using lower case for header keywords. In SFITSIO, a
keyword of the FITS header in upper case and that in lower case are distinguished. For example,
following header records can be created.
¨

FOO
§Foo

10.3

¥

= 123
= 456

¦

Long keyword in the header (maximum 54 characters)

Current FITS standard does not permit using keyword having more than 8 characters, therefore,
9th character of a header record should be “=” or white space except records having
8-space keyword. This means that other cases are not defined about 9th characters in FITS
standard.
Therefore, we can create a convention for undefined 9th characters, and this leads to a long
keyword convention:
1. When 9th character of a header record is not “=” or white space, the record has a long
keyword having more than 8 characters.
2. Long keywords should not have “=” or white space.
This convention keeps readability of FITS header, and does not cause any compatibility problems
when handling old FITS files.
Following above convention, the long keyword can be saved simply in SFITSIO:¨¥

TTYPE12345= ’Mag
TFORM12345= ’1D§’’/ column name/ data format : 8-byte REAL

The keyword is up to 54 characters33) and “=” or space cannot be used.
33)

To store a maximum or minimum 64-bit integer value and a comment string whose length is 1, length of
keyword must be 54.

¦

Ver. 1.2.1

75

In ESO’s convention, the header record of the long keyword is labeled HIERARCH, however, thisway is not sophisticated.

10.4

Number of columns of the ASCII table or the binary table that exceed
999

Header keywords of 8 characters in FITS standard limit the number of column definitions up to
999 in ASCII table or binary table.
By the extension of long keyword described in the previous section, number of columns of
ASCII table or binary table is unlimited in SFITSIO.

10.5

Applying CONTINUE keyword for long comment string

COMMENT records are useful to store a long description into FITS header. However, FITS libraries
cannot know which header records are explained by such COMMENT strings. This will prevent
automatic processing about FITS header, therefore, comments and descriptions should be written
after “/” character in normal header records.
On the other hand, there is a problem that a comment string after “/” is not saved completely
with simple format algorithm, if the record has long string value.
To solve this problem, SFITSIO allocates enough comment area using new record with CONTINUE
keyword at the end of a long string value like this:¨

TELEM34 = ’BAD_FRAME,UNDEF_ANOM_FRAME,BLANK,IN_SAA,NEAR_MOON,UNTRUSTED_FRAME&’
CONTINUE ’’ / element names§
If the comment area is not still enough to save a comment string completely, SFITSIO saves along comment string using CONTINUE keyword. Here is an example:¨

MESSAGE = ’FITS (Flexible Image Transport System) format is defined in &’CONTINUE ’"Astronomy and Astrophysics", volume 376, page 359; bibcode: &’CONTINUE ’2001A&A...376..359H’ / In SFITSIO, this message is not written &CONTINUE automatically. Therefore, SFITSIO is not CFITSIO :-)

§

¥
¦

¥

¦

This extension was devised by L1TSD project of ISAS/JAXA.

10.6

Definition of new line characters in a string value in FITS header

Column descriptions of binary table or ASCII table is often converted into HTML, VOTable,
LATEX format, etc. To convert such descriptions into other formats automatically, column descriptions, annotations, etc. should be stored in string values with unique keywords rather than
COMMENT records. In this case, we have to define new line characters to keep uniformity in various
formats.
In SFITSIO, “\n”("\\n" in C) in a header record is defined as new line characters, and built-in
formatter splits a long string value into some header records using new line characters in it. Hereis an example:¨¥

TDESC3 = ’Trigger type flag,\n&’CONTINUE ’ b1000000:SUD(trigd by SuperUpper Discriminator),\n&’CONTINUE ’ b0100000:ANODE,\n&’CONTINUE ’ b0010000:PIN0 b0001000:PIN1 b0000100:PIN2,\n&’CONTINUE ’ b0000010:PIN3 b0000001:PSEUDO’ / description of column§

This extension was devised by L1TSD project of ISAS/JAXA.

¦

76

10.7

SFITSIO User’s Reference Guide

Declaration of new column keywords of the ASCII or binary table

New header keywords that express properties of table column (field) are often defined in various
institutes. For example, TLMINn and TLMAXn are representative keywords.
However, FITS libraries cannot know whether they are column keywords or not. Therefore,
when FITS libraries erase or move some columns in ASCII or binary tables, newly defined column
keywords are not erased or not copied properly. Additional problem is that information of FITS
tables are not automatically converted into other formats such as HTML, VOTable, LATEX, etc.
To solve this problem, we defined “TXFLDKWD” keyword to indicate new column keywords for
FITS libraries. We show an example to append TLMINn, TLMAXn, TALASn, TELEMn and TDESCn
column keywords:¨¥

TXFLDKWD= ’TLMIN,TLMAX,TALAS,TELEM,TDESC’ / extended field keywords§¦

TXFLDKWD should be written before standard column keywords such as TTYPEn.
This extension was devised by L1TSD project of ISAS/JAXA.

10.8

Definition of an alias of the ASCII table or the binary table

An alias of the column can be defined by using keyword TALASn as follows.
¨

TTYPE4TALAS4§= ’QUATERNION’= ’AOCU_ADS_Q’/ Quaternion at boresight/ aliases of column name¥¦

In case that multiple aliases need to be defined, define them in csv format. Of course, the Alias
defined here is also available in the APIs of SFITSIO.
This extension was devised by ‘AKARI’ project of ISAS/JAXA.

10.9

Definition of an element name in the column of the binary table

In SFITSIO, each element in the column having array of the binary table can be named as follows.
¨¥

TTYPE34 = ’FLAG’/ Flag for detector condition
TELEM34 = ’BAD_FRAME,UNDEF_ANOM_FRAME,BLANK,IN_SAA,NEAR_MOON,UNTRUSTED_FRAME&’
CONTINUE ’’ / element names
TFORM34 = ’8X’/ data format : BIT§¦

Each name of the element can be defined in the record of TELEMn keyword in the csv format. It
is not necessarily that all elements should be named. If omitting some name definitions, someelements of right side are not named. Although this example shows the case for bit type, TELEMn
expression can also be used for other types (e.g., integer, real, etc.).
In the SFITSIO APIs, the data value can be read or written by giving these element names tothe argument of the member function such as dvalue() or assign().
This extension was devised by ‘AKARI’ project of ISAS/JAXA.

10.10

Definition of the number of bits in the column of the binary table

In case that the column has array of bit type (i.g., TFORMn is ’mX’), a bit width of an element canbe defined by giving bit-field description like struct of C-language (or giving multiple same namesof the element) to the value of TELEMn.
An example is shown below:

Ver. 1.2.1¨

TTYPE36 = ’QUALITY ’/ Quality for each pixel condition
TFORM36 = ’4000X’/ data format : BIT
TDIM36 = ’(40,100)’TELEM36 = ’QUAL_CV_PARAM:2,QUAL_RC_PARAM:2,QUAL_RC_CF:2,QUAL_DF_EQ:2,&’
CONTINUE ’QUAL_RP_DATA:2,QUAL_RP_PARAM:2,QUAL_RP_TABLE:2,QUAL_FF_PARAM:2,&’
CONTINUE ’QUAL_FF_CF:2,QUAL_GPGL_CORR:2,QUAL_MTGL_CORR:2,QUAL_TR_HIST:2,&’
CONTINUE ’QUAL_TR_PARAM:2,QUAL_DK_DATA:2,QUAL_DK_PARAM:2,QUAL_DK_TABLE:2,&’
CONTINUE ’QUAL_FX_CORR:2,QUAL_FX_PARAM:2,,,,’ / element names

§

77
¥

¦

In this case, the definition about TTYPE36, TFORM36 and TDIM36 meets FITS standard, and a cellin the field has bits of 40 × 100. TELEM36 gives the names of elements and bit width (2-bit) of
each element. It is not necessarily that all elements should be named. If omitting some namedefinitions, some elements of right side are not named. The element names can have ‘:’ character,however, it should not be used in terms of future compatibility problems.
In the SFITSIO APIs, integer values (up to 32-bit) having a bit width defined here can beread or written. SFITSIO copies the column data in a FITS file into memory buffer without
modifying original byte data. Therefore, using bit-field extension can reduce file size and memory
consumption.
This extension was devised by ‘AKARI’ project of ISAS/JAXA.

78

11

SFITSIO User’s Reference Guide

Unsupported FITS Standard and Limitation

Random groups structure of FITS standard is unsupported by the SFITSIO.
Member functions for file I/O and template input support complex numbers and variable length
array in the binary table. However, current version of SFITSIO does not provide high-level APIs
to read and write cells of complex numbers or variable length array. To handle it, programmers
have to write codes using low-level APIs.

Ver. 1.2.1

79

12Reference

12.1

Constants

In namespace sli, namespace FITS, and constants required to treat FITS files, were defined. In
the user’s code, the values themselves of the constants should not be written.
To indicate the kind of HDU, use following constants.
Type
const int
const int
const int

Constants in the SFITSIOFITS::IMAGE_HDU
FITS::ASCII_TABLE_HDU
FITS::BINARY_TABLE_HDU

Value
0
1
2

To indicate the state of user header record, use following constants.
Type
const int
const int
const int

Constants in the SFITSIOFITS::NULL_RECORD
FITS::NORMAL_RECORD
FITS::DESCRIPTION_RECORD

Value
0
1
2

To indicate the kind of data, use following constants.
Type
const int
const int
const int
const int
const int
const int
const int
const int
const int
const int
const int
const int
const int
const int
const int

12.2

Constants in the SFITSIOFITS::BIT_T
FITS::BYTE_T
FITS::LOGICAL_T
FITS::BOOL_T
FITS::ASCII_T
FITS::STRING_T
FITS::SHORT_T
FITS::LONG_T
FITS::LONGLONG_T
FITS::FLOAT_T
FITS::DOUBLE_T
FITS::COMPLEX_T
FITS::DOUBLECOMPLEX_T
FITS::LONGARRDESC_T
FITS::LLONGARRDESC_T

Value
88
66
76
76
65
65
73
74
75
69
68
67
77
80
81

Image
°

°
°
°
°
°

Binary Table
°
°
°
°
°
°
°
°
°
°
°
°
°
°
°

Types

The namespace fits and data types required to treat FITS files are defined in the namespace
sli.

80

SFITSIO User’s Reference Guide
To access raw data of the FITS file, use following types.
Types
fits::bit_tfits::byte_tfits::logical_t
fits::short_t
fits::long_t
fits::longlong_t
fits::float_t
fits::double_t
fits::complex_tfits::doublecomplex_tfits::ascii_t
fits::longarrdesc_t
fits::llongarrdesc_t

Types used actually
struct _bit_t
uint8_tuint8_t
int16_tint32_tint64_t
float
doublefloat _Complex
double _Complex
charstruct _longarrdesc_t
struct _llongarrdesc_t

Image
°
°
°
°
°
°

Binary Table
°
°
°
°
°
°
°
°
°
°
°
°
°

To define the FITS header, use following structures.
Types

fits::header_def

Definition of structure
struct {const char *keyword;
const char *value;
const char *comment;}

To define the column of ASCII table and Binary table, use following structures.
Types

fits::table_def

Definition of structure
struct {const char *ttype;
const char *ttype_comment;
const char *talas;
const char *telem;
const char *tunit;
const char *tunit_comment;
const char *tdisp;const char *tform;
const char *tdim;
const char *tnull;
const char *tzero;
const char *tscal;}

Ver. 1.2.1

12.3

81

Operation of whole FITS

In this section, we describe APIs to perform a stream input/output and to operate the configurationof the HDU.
12.3.1

read stream()

NAME
read stream() — Read from stream
SYNOPSIS
ssize_t read_stream( const char *path );ssize_t readf_stream( const char *path_fmt, ... );ssize_t vreadf_stream( const char *path_fmt, va_list ap );DESCRIPTIONThis member function reads the FITS file specified by path or URL (supporting for file://,http://, ftp://) and imports its whole content to the object. Judging from the file nameof path or MIME header obtained from http server, in case of necessity, zlib or bzlib areused for the reading34) . In case that the files are retrieved from a ftp server, user nameand password can be set to path in the form of ftp://username:password@hostname/... Ifneither username nor password is set, the API accesses the server anonymously.
If hdus_to_read().assign() or cols_to_read().assign()(§12.3.2) are called before thismember function is used, specific HDU, or a specific column of ASCII table or of Binary
table can be read.
In case of readf stream() member function, arguments after path_fmt should be the set in thesame manner as that of printf() in libc. Refer §12.4.9 about the format of the printf().
PARAMETER[I] path
File name (URL name)[I] path_fmt Format specification of the file name (URL name)[I] ...
Each element data of the file name (URL name)[I] apAll element data of the file name (URL name)([I] : input, [O] : output)
RETURN VALUE
Non-negative value:

Negative value:

Byte size of the read stream (In case of compressed file, size after
extracted)
Error (Failed to read the stream, e.g., because the file was notfound)

EXCEPTION
In case that a fatal error occurs (for example, memory capacity is not enough for a specified FITS file and buffer cannot be allocated), the API throws an exception(sli::err_rec
exception) from classes composing sfitsio and classes provided by SLLIB.
EXAMPLES
See the EXAMPLES in §12.3.2 or §5.2, §5.3 in Tutorial.

34)

This function is carried out in digeststreamio class of SLLIB. Detail in APPENDIX4 (§16)

82

SFITSIO User’s Reference Guide

12.3.2hdus to read().assign(), cols to read().assign()

NAME
hdus to read().assign(), cols to read().assign() — Specification of HDU or column to be readfrom stream
SYNOPSIS
tarray_tstring &hdus_to_read().assign( const char *hdu0, const char *hdu1, ... );tarray_tstring &hdus_to_read().assign( const char *hdus[] );tarray_tstring &cols_to_read().assign( const char *col0, const char *col1, ... );tarray_tstring &cols_to_read().assign( const char *cols[] );DESCRIPTION
By using these member functions before read stream() member function (§12.3.1), only aspecific HDU, or a specific column of an ASCII table or a Binary table can be read. (Onlythe reading of a Primary HDU, however, cannot be skipped.) For the argument, a HDU
name, a column name of an ASCII table or a Binary table should be listed and terminated
by NULL.
If all HDUs or all columns are necessary, use hdus_to_read().init() or cols_to_read().init(),respectively. A value set by these member functions can be erased by init() member function(§12.3.15).
PARAMETER[I] hdu0,hdu1...
[I] hdus[][I] col0,col1...

HDU name (specify NULL for the terminal)
Array of HDU name (specify NULL for the terminal)
Column name of Binary or ASCII table (specify NULL for the terminal)[I] cols[]
Array of column name of Binary or ASCII table (specify NULL for
the terminal)([I] : input, [O] : output)

RETURN VALUEThis API returns a reference to tarray_tstring object including set HDU name or column
name.
EXCEPTION
In case that this API fails to reserve inner buffer, it throws an exception derived fromSLLIB (sli::err_rec exception).
EXAMPLES
Following code reads the Primary HDU and the FIS OBS HDU, and only columns named as“AFTIME”, “DET”, “RA” and “DEC” of the Binary table.
fitscc fits;/* Required HDUs */fits.hdus_to_read().assign("Primary","FIS_OBS",NULL);/* Required columns in binary tables */fits.cols_to_read().assign("AFTIME","DET","RA","DEC",NULL);/* Reading a file */r_size = fits.readf_stream("my_file_no.%d.fits.gz",i);Ver. 1.2.1
12.3.383

write stream()

NAME
write stream() — Write to a stream
SYNOPSIS
ssize_t write_stream( const char *path );ssize_t writef_stream( const char *path_fmt, ... );ssize_t vwritef_stream( const char *path_fmt, va_list ap );DESCRIPTION
write stream() writes all content of an object to a file specified by path. Judging from thefile name of path, in case of necessity, zlib or bzlib are used for the writing35) . In case thatthe files are put to a ftp server, user name and password can be set to path in the form of
ftp://username:password@hostname/. If neither username nor password is set, the API
accesses the server anonymously.
In case of writef stream() member function, arguments after path_fmt should be set samewith that of printf() in libc.
PARAMETER[I] path
File name (URL name)[I] path_fmt Format specification of the file name (URL name)[I] ...
Each element data of the file name (URL name)[I] apAll element data of the file name (URL name)([I] : input, [O] : output)
RETURN VALUE
Non-negative value:

Negative value:

Byte size of the written stream (In case of compressed file, size
after extracted)
Error (Failed to write the stream, e.g., because of invalid permission)

EXCEPTION
If the API fails to operate memory buffer or to output into a file (for example, unexpected
error at the writing to output file), it throws an exception derived from SLLIB (sli::err_rec
exception).
EXAMPLES
Following code writes whole content of the fits object to the file my_file_no.1.fits.bz2,
for example in case that i=1. In this case, because the suffix is “.bz2”, the file is compressed
via bzip2.
fitscc fits;
w_size = fits.writef_stream("my_file_no.%d.fits.bz2",i);Other examples are shown in §5.2 and §5.3 in Tutorial.

35)

This function is carried out in digeststreamio class of SLLIB. Detail in APPENDIX4 (§16)

84

SFITSIO User’s Reference Guide

12.3.4access stream()

NAME
access stream() — Access to a stream
SYNOPSIS
ssize_t access_stream( const char *path );ssize_t accessf_stream( const char *path_fmt, ... );ssize_t vaccessf_stream( const char *path_fmt, va_list ap );DESCRIPTION
An argument of access stream() member function should be set with the style of open() of
Perl. If the argument path indicates a file or a URL, access stream() reads FITS content
from it or writes FITS content to it. If the argument path indicates a command-line, access stream() executes the commands, creates a pipe-connection to commands, and reads
FITS content from the pipe or writes FITS to the pipe36) .
When the argument path does not indicate commands, “<” or “>” should be set at the firstcharacter of the argument string. For example, "< infile.fits" shows reading the file“infile.fits” (see EXAMPLE-1) and "> outfile.fits" shows writing the file “outfile.fits”.
Neither “<” nor “>” is found, the file path will be read. Compressed files (gzip or bzip2) will
be decompressed automatically.
When the argument path indicates commands, the commands should include “|” or “|” at
the first or the last character of the argument string. If “|” is placed at the last characterof the argument, access stream() executes the commands in the argument, creates a pipeconnection to commands, and reads FITS content from the pipe. If “|” is placed at the firstcharacter of the argument, access stream() executes the commands in the argument, createsa pipe-connection to commands, and write FITS content to the pipe (see EXAMPLE-2).
The member function access stream() executes the commands as “/bin/sh -c command”.
Therefore, “|”, “<” and “>” can be included in the path (see EXAMPLE-2).
In case of accessf stream() member function, arguments after path_fmt should be set samewith that of printf() in libc.
PARAMETER[I] path
File name (URL name) or command line
[I] path_fmt Format specification of the file name (URL name) or command line
[I] ...
Each element data of the file name (URL name) or command line
[I] apAll element data of the file name (URL name) or command line([I] : input, [O] : output)
RETURN VALUE
Non-negative value:

Negative value:

Byte size of the written or read stream (In case of compressed file,size after extracted)
Error (Failed to read the stream, e.g., because the file was notfound)
Error (Failed to write the stream, e.g., because of invalid permission)

EXCEPTION
If the API fails to operate memory buffer or to output into a file (for example, unexpected
error at the writing to output file), it throws an exception derived from SLLIB (sli::err_rec
exception).
36)

This function is carried out in digeststreamio class of SLLIB. Detail in APPENDIX4 (§16)

Ver. 1.2.1

85

EXAMPLE-1
Following code reads whole content of the FITS file my_file.fits.bz2. In this case, because
the suffix is “.bz2”, the file is compressed via bzip2.
fitscc fits;
r_size = fits.access_stream("< my_file.fits.bz2");
EXAMPLE-2
Following code read a FITS file using the connection of the HTTP over SSL.
fitscc fits;
r_size = fits.accessf_stream("wget -O - %s | gzip -dc |","https://foo/secret.fits.gz");
Other examples are shown in §5.4 in Tutorial. The tutorial shows some examples for the useof a compression tool with multi-threading support.

12.3.5read template()

NAME
read template() — Read a FITS template
SYNOPSIS
ssize_t read_template( int flags, const char *path );ssize_t vreadf_template( int flags, const char *path_fmt, va_list ap );ssize_t readf_template( int flags, const char *path_fmt, ... );DESCRIPTIONThis member function reads the FITS template file (See §8) specified by path or URL (supporting for file://, http://, ftp://) and creates FITS content to the object that has nodata contents in pixels or cells. Judging from the file name of path or MIME header obtained
from http server, in case of necessity, zlib or bzlib are used for the reading. In case that thefiles are retrieved from a ftp server, user name and password can be set to path in the form of
ftp://username:password@hostname/... If neither username nor password is set, the API
accesses the server anonymously.
In case of readf template() member function, arguments after path_fmt should be the set
in the same manner as that of printf() in libc. Refer §12.4.9 about the format of theprintf().
PARAMETER[I] flags
Flags to switch the behavior (currently unused; always 0 should be set)[I] path
File name (URL name)[I] path_fmt Format specification of the file name (URL name)[I] ...
Each element data of the file name (URL name)[I] apAll element data of the file name (URL name)([I] : input, [O] : output)
RETURN VALUE
0
Negative value::

Successfully finished.
Error (Failed to read the stream, e.g., because the file was not found)86

SFITSIO User’s Reference Guide

EXCEPTION
In case that a fatal error occurs (for example, memory capacity is not enough for a specified FITS file and buffer cannot be allocated), the API throws an exception(sli::err_rec
exception) from classes composing sfitsio and classes provided by SLLIB.
EXAMPLES
fitscc fits;
status = fits.read_template(0, "template/image1.tpl");See §8 for details of SFITSIO template files.

12.3.6stream length()

NAME
stream length() — Return a file size to be written to a stream
SYNOPSIS
ssize_t stream_length();DESCRIPTION
stream length() realign the system header and return the size of a file written by write stream().
RETURN VALUE
Non-negative value
Negative value::

Size to be written to stream.
Error. (only in debug mode)

EXCEPTION
If the API fails to handle string because of lack of memory, it throws an exception derived
from SLLIB (sli::err_rec exception).
EXAMPLES
fitscc fits;
w_size = fits.stream_length();12.3.7

length()NAME
length() — Number of HDUSYNOPSIS
long length() const;
RETURN VALUE
length() returns number of HDU.
EXAMPLES
long hdu_count = fits.length();See also the example in §5.2 in Tutorial.

Ver. 1.2.1
12.3.887

fmttype()NAME
fmttype() — Format type name
SYNOPSIS
const char *fmttype() const;
DESCRIPTION
fmttype() returns a format type name. If the format type name is not set, it returns NULL.
Since return value is an address of an object’s internal buffer, it is invalid in case that object
is deleted or its name is changed.
For more information about format type name, see §10.1.
RETURN VALUE
fmttype() returns an address of a format type name.
EXAMPLES
printf("Format Type = %s\n", fits.fmttype());

12.3.9ftypever()

NAME
ftypever() — Version number of format typeSYNOPSIS
long long ftypever() const;
RETURN VALUE
ftypever() returns version number of format type.
EXAMPLES
printf("Verson of Format Type = %lld\n", fits.ftypever());

12.3.10hduname(), extname()

NAME
hduname(), extname() — HDU name
SYNOPSIS
const char *hduname( long index ) const;
const char *extname( long index ) const;
DESCRIPTION
hduname() and extname() return HDU name specified by index. If HDU name is not set,
they return NULL.
Since return value is an address of an object’s internal buffer, it is invalid in case that object
is deleted or its name is changed.
PARAMETER[I] index index of HDU([I] : input, [O] : output)

88

SFITSIO User’s Reference Guide

RETURN VALUE
hduname(), extname() return an address of HDU name.
EXAMPLES
Following code lists all HDU names to standard output.
long i;for ( i=0 ; i < fits.length() ; i++ ) {printf("HDU[%ld] Name is %s\n", i, fits.hduname(i));}
See also the example in §5.2 in Tutorial.
12.3.11

hduver(), extver()NAME
hduver(), extver() — HDU version
SYNOPSIS
long long hduver( long index ) const;
long long hduver( const char *name ) const;
long long extver( long index ) const;
long long extver( const char *name ) const;
DESCRIPTION
hduver(), extver() return HDU version specified by index or name.
PARAMETER[I] index HDU index[I] name
HDU name([I] : input, [O] : output)
RETURN VALUE
hduver(), extver() return HDU version.
EXAMPLES
Following code lists all HDU versions to standard output.
long i;for ( i=0 ; i < fits.length() ; i++ ) {printf("HDU[%ld] Version is %lld\n", i, fits.hduver(i));}
12.3.12hdulevel(), extlevel()NAME
hdulevel(), extlevel() — HDU level
SYNOPSIS
long long hdulevel( long index ) const;
long long hdulevel( const char *name ) const;
long long extlevel( long index ) const;
long long extlevel( const char *name ) const;

Ver. 1.2.1

89

DESCRIPTION
hdulevel(), extlevel() return HDU level (value of EXTLEVEL in FITS header) specified byindex or name.
PARAMETER[I] index HDU index[I] name
HDU name([I] : input, [O] : output)

12.3.13

hdutype(), exttype()

NAME
hdutype(), exttype() — HDU typeSYNOPSIS
int hdutype( long index ) const;
int hdutype( const char *name ) const;
int exttype( long index ) const;
int exttype( const char *name ) const;
DESCRIPTION
hdutype(), exttype() return HDU type specified by index or name.
Return value is FITS::IMAGE_HDU, FITS::ASCII_TABLE_HDU, or FITS::BINARY_TABLE_HDU.
PARAMETER[I] index HDU index[I] name
HDU name([I] : input, [O] : output)
RETURN VALUE
hdutype(), exttype() return HDU type.
EXAMPLES
switch ( fits.hdutype(index) ) {case FITS::IMAGE_HDU:
printf("This is an image HDU!\n");break;
case FITS::ASCII_TABLE_HDU:
printf("This is an ASCII table HDU!\n");break;
case FITS::BINARY_TABLE_HDU:
printf("This is a Binary table HDU!\n");break;
default:
printf("This is an unknown type HDU!\n");break;}
12.3.14index()

NAME
index() — HDU index

90

SFITSIO User’s Reference GuideSYNOPSIS
long index( const char *name ) const;
long indexf( const char *name_fmt, ... ) const;
long vindexf( const char *name_fmt, va_list ap ) const;
DESCRIPTION
index() returns HDU index specified by name.
Only when "Primary" is specified for HDU name, they always return 0 if the Primary HDU
exists even if header keyword EXTNAME is not set.
They return negative value if specified name is not found.
Arguments after name_fmt can be set same with that of printf().
PARAMETER[I] name
HDU name[I] name_fmt Format string of HDU name[I] ...
All element data of the HDU name[I] apAll element data of the HDU name([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value::

HDU index specified by name.
Error (If specified name is not found.)EXCEPTION
If the API fails to operate memory buffer at conversion of a format string, it throws an
exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
Following code acquire the HDU index specified by HDU name.
long index;
index = fits.index("FIS_OBS");12.3.15

init()

NAME
init() — Initialization of object
SYNOPSIS
fitscc &init();fitscc &init( const fitscc &obj );DESCRIPTION
init() deletes all content of an object and initialize it. In case that the argument obj is given,
it copies all contents of the object obj to the own object that calls init().
PARAMETER[I] obj fitscc object copied at initialization.
([I] : input, [O] : output)
RETURN VALUE
init() returns a reference to its own object.

Ver. 1.2.1

91

EXCEPTION
If the API fails to operate internal memory buffer (for example, obj’s data is too big forfree memory area), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES/* Initialize Fits Object!! */fits.init();12.3.16

append image()

NAME
append image() — Append an Image HDUSYNOPSIS
fitscc &append_image( const char *hduname, long long hduver,
int type, long naxis0, long naxis1 = 0, long naxis2 = 0 );fitscc &append_image( const char *hduname, long long hduver,
int type, long naxisx[], long ndim );fitscc &append_image( const char *hduname, long long hduver,const fits_image &src );fitscc &append_image( const fits_image &src );DESCRIPTION
append image() append an Image HDU. Argument hduname specify the name of HDU andhduver specifies its version. These values are reflected to EXTNAME and EXTVER in a FITS
header. If NULL is given to hduname, this function can be invalid; giving NULL, however, is
not recommended for use of SFITSIO.
As type, any one of FITS::DOUBLE_T, FITS::FLOAT_T, FITS::LONGLONG_T, FITS::LONG_T,
FITS::SHORT_T and FITS::BYTE_T should be given.
To naxis0, naxis1 and naxis2, specify the number of pixels of x axis, y axis and z axis.
naxis1 and naxis2 can be omitted. However,if only naxis0 is given, the image is regarded as
one dimension, and if naxis0 and naxis1 is given, the image is regarded as two dimensions.
If the image exceeds three dimensions, naxisx and ndim are specified.
PARAMETER[I] hduname HDU name[I] hduver
HDU version[I] type
HDU type[I] naxis0
Number of pixels of X axis
[I] naxis1
Number of pixels of Y axis
[I] naxis2
Number of pixels of Z axis
[I] naxisx
List of number of pixels of each axis
[I] ndim
Number of elements of naxisx[I] src
Image object to be appended([I] : input, [O] : output)
RETURN VALUE
append image() returns a reference to itself.
EXCEPTION
If the API fails to operate internal memory buffer (for example, image data is too big for

92

SFITSIO User’s Reference Guide
free memory area), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).

EXAMPLES
Following code appends double-typed 1024 × 1024 Image HDU of which HDU name is ”XBAND” and HDU version is 100 to the object fits.
fits.append_image("X-BAND", 100,

FITS::DOUBLE_T, 1024, 1024);

See also the example in §5.9 in Tutorial.
12.3.17

append table()

NAME
append table() — Append the Ascii Table HDU or the Binary Table HDUSYNOPSIS
fitscc &append_table( const char *hduname, long long hduver,const fits::table_def defs[], bool ascii = false );fitscc &append_table( const char *hduname, long long hduver,const fits_table &src );fitscc &append_table( const fits_table &src );DESCRIPTION
append table() appends the Ascii Table HDU or the Binary Table HDU. If the argument
ascii is set to true, Ascii Table HDU is appended. HDU name and its version is specified
to the arguments hduname and hduver, respectively. These values are reflected to EXTNAME
and EXTVER in the FITS header. If NULL is specified to the hduname, this function can beinvalid, however, giving NULL is not recommended for use of SFITSIO.
By using defs, Definition of Ascii Table or Binary Table is specified. Members of fits::table_def
structure are following:
typedef struct {const char *ttype;/* column name */const char *ttype_comment;
const char *const *talas;/* column alias */const char *const *telem;/* element name */const char *tunit;/* physical unit */const char *tunit_comment;
const char *tdisp;/* display format */const char *tform;/* column type */const char *tdim;/* specification of array */const char *tnull;/* value of blank */const char *tzero;/* zero point */const char *tscal;/* scaling factor */const char *theap;/* (unsupported) */} fits::table_def;
Since the keywords in the Binary Table header is used for this structure’s definition as it
is, in case of the Binary Table, values of TTYPEn, TFORMn, and so on, can be replaced tocorresponding members directly.
On the other hand, in case of the Ascii Table, note that member names of this structure do
not correspond one-to-one with keyword names in the header. At first, to tform, string lengthVer. 1.2.1

93

of column must be specified in the form of “number + A”, for example, "16A". (A format
such as "120A10", however, cannot be used.) Giving telem and tdim does not make sense.
TFORMn in the Ascii Table is given to tdisp and this is utilized as a format of conversion
from a value of an argument to string when the value of the argument (number or string) of
the SFITSIO’s member function is written to Ascii Table. Assignable format is
Aw, Iw, Fw.d, Ew.d or Dw.d.
NULL or "" should be given to a term which does not need to be assigned. THEAP is notsupported in the SFITSIO. At the last of array defs, all members need to be NULL.
PARAMETER[I] hduname HDU name[I] hduver
HDU version[I] defs
fits::table_def structure[I] ascii
Type of Table HDU to be appended(false:Binary true:Ascii)[I] src
Table object to be appended([I] : input, [O] : output)
RETURN VALUE
append table() returns a reference to itself.
EXCEPTION
If the API fails to operate internal memory buffer (for example, table data to be appended
is too big for free memory area), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
Following code appends the Binary Table HDU of which HDU name is “EVENT” and HDU
version is 100, defined by structure array def, to the object fits.
const fits::table_def def[] = {// TTYPE,comment, talas, telem, TUNIT,comment, TDISP, TFORM, TDIM{ "TIME","satellite time", NULL, NULL, "s","", "D16.3", "1D", "" },{ "NAME","", NULL, NULL, "","", "", "128A16", "(4,2)" },{ NULL }};fits.append_table("EVENT", 100, defs);
See also the examples in §5.15 and §5.16 in Tutorial.

12.3.18

insert image()

NAME
insert image() — Insert an Image HDUSYNOPSIS
fitscc &insert_image( long index0,
const char *hduname, long long hduver,
int type, long naxis0, long naxis1 = 0, long naxis2 = 0 );fitscc &insert_image( long index0,
const char *hduname, long long hduver,
int type, long naxisx[], long ndim );94

SFITSIO User’s Reference Guide
fitscc &insert_image( const char *hduname0,
const char *hduname, long long hduver,
int type, long naxis0, long naxis1 = 0, long naxis2 = 0 );fitscc &insert_image( const char *hduname0,
const char *hduname, long long hduver,
int type, long naxisx[], long ndim );fitscc &insert_image( long index0,
const char *hduname, long long hduver,const fits_image &src );fitscc &insert_image( const char *hduname0,
const char *hduname, long long hduver,const fits_image &src );fitscc &insert_image( long index0, const fits_image &src );fitscc &insert_image( const char *hduname0, const fits_image &src );DESCRIPTION
insert image() inserts Image HDU to a HDU specified by index0 or hduname0.
Specifications of arguments after hduname are same as the case of append_image()(§12.3.16).
PARAMETER[I] index0
HDU index which designate insert position[I] hduname0 HDU name which designate insert position[I] hduname
HDU name[I] hduver
HDU version[I] type
HDU type[I] naxis0
Number of pixels of X axis
[I] naxis1
Number of pixels of Y axis
[I] naxis2
Number of pixels of Z axis
[I] naxisx
List of Number of pixels of each axis
[I] ndim
Number of elements of naxisx[I] src
Image object to be inserted([I] : input, [O] : output)
RETURN VALUE
insert image() returns a reference to itself.
EXCEPTION
If the API fails to operate internal memory buffer (for example, image data to be inserted
is too big for free memory area), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
Following code inserts double-typed 1024 × 1024 Image HDU of which name is “X-TABLE”
and version is 100 in front of HDU “X-BAND”.
fits.insert_image("X-BAND",12.3.19"X0-BAND", 100, FITS::DOUBLE_T, 1024, 1024);

insert table()

NAME
insert table() — Insert an Ascii Table or a Binary Table

Ver. 1.2.1

95

SYNOPSIS
fitscc &insert_table( long index0,
const char *hduname, long long hduver,const fits::table_def defs[], bool ascii = false );fitscc &insert_table( const char *hduname0,
const char *hduname, long long hduver,const fits::table_def defs[], bool ascii = false );fitscc &insert_table( long index0,
const char *hduname, long long hduver,const fits_table &src );fitscc &insert_table( const char *hduname0,
const char *hduname, long long hduver,const fits_table &src );fitscc &insert_table( long index0, const fits_table &src );fitscc &insert_table( const char *hduname0, const fits_table &src );DESCRIPTION
insert table() inserts an Ascii Table HDU or a Binary Table HDU into an HDU specified byindex0 or hduname0.
However, it cannot insert into a Primary HDU.
Specifications of arguments after hduname are the same as in case of of append_table()(§12.3.17).
PARAMETER[I] index0
HDU index which designate insert position[I] hduname0 HDU name which designate insert position[I] hduname
HDU name[I] hduver
HDU version[I] defs
fits::table_def structure[I] ascii
type of Table HDU to be inserted (false: Binary, true: Ascii)[I] src
table object to be inserted([I] : input, [O] : output)
RETURN VALUE
insert table() returns a reference to itself.
EXCEPTION
If the API fails to operate internal memory buffer (for example, the table data to be inserted
is too big for free memory area), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
Following code inserts table HDU of which name is “X-TABLE” and version is 100, definedby structure array defs, in front of HDU “X-BAND”. (Refer EXAMPLES in §12.3.17 forstructure array defs.)
fits.insert_table("X-BAND",12.3.20

erase()

NAME
erase() — Erase a HDU"X-TABLE", 100, defs);

96

SFITSIO User’s Reference GuideSYNOPSIS
fitscc &erase( long index );fitscc &erase( const char *hduname );DESCRIPTION
erase() erases a HDU specified by index or hduname.
However, it cannot erase a Primary HDU if the next HDU of the Primary HDU is not an
Image HDU.
PARAMETER[I] index
HDU index to be erased[I] hduname HDU name to be erased([I] : input, [O] : output)
RETURN VALUE
erase() returns a reference to itself.
EXCEPTION
If the API fails to operate internal memory buffer, it throws an exception derived fromSLLIB or SFITSIO (sli::err_rec exception).
EXAMPLES
fits.erase("X-BAND");

12.3.21

assign fmttype()

NAME
assign fmttype() — Change a format type name
SYNOPSIS
fitscc &assign_fmttype( const char *fmttype, long long ftypever );DESCRIPTION
assign fmttype() changes a format type name. The argument fmttype is a string which
defines a globally unique data format and ftypever gives its version. These values arereflected to FMTTYPE and FTYPEVER in a Primary HDU header.
fmttype and ftypever can be utilized for validity check of a FITS when the FITS is readfrom a file.
See §10.1 for more information about format type.
PARAMETER[I] fmttype
format type name to be set[I] ftypever format type version to be set([I] : input, [O] : output)
EXCEPTION
If the API fails to operate internal memory buffer, it throws an exception derived fromSLLIB or SFITSIO (sli::err_rec exception).
RETURN VALUE
assign fmttype() returns a reference to itself.

Ver. 1.2.1

97

EXAMPLES
fits.assign_fmttype("ASTRO-X ALL-SKY SURVEY IMAGE", 101);
See also the examples in §5.9, §5.15 and §5.16 in Tutorial.
12.3.22

assign ftypever()NAME
assign ftypever() — Change a format type version
SYNOPSIS
fitscc &assign_ftypever( long long ftypever );DESCRIPTION
assign ftypever() changes a format type version. The value is reflected to FTYPEVER in a
primary HDU header.
fmttype and ftypever can be utilized for validity check of a FITS when the FITS is readfrom a file.
PARAMETER[I] ftypever version of format type to be set([I] : input, [O] : output)
RETURN VALUE
assign ftypever () returns a reference to itself.
EXAMPLES
fits.assign_ftypever(102);12.3.23

assign hduname(), assign extname()

NAME
assign hduname(), assign extname() — Change a HDU name
SYNOPSIS
fitscc &assign_hduname( long index, const char *name );fitscc &assign_extname( long index, const char *name );DESCRIPTION
assign hduname() or assign extname changes the HDU name specified by index. name isreflected to EXTNAME in a header. The name of Primary HDU can also be specified.
PARAMETER[I] index HDU index which designates HDU whose name is to be changed[I] name
HDU name to be set([I] : input, [O] : output)
EXCEPTION
If the API fails to operate internal memory buffer, it throws an exception derived fromSLLIB or SFITSIO (sli::err_rec exception).
RETURN VALUE
assign hduname() or assign extname returns a reference to itself.
EXAMPLES
fits.assign_hduname("X-BAND");

98

SFITSIO User’s Reference Guide

12.3.24

assign hduver(), assign extver()NAME
assign hduver() — Change a HDU version number
SYNOPSIS
fitscc &assign_hduver( long index, long long ver );fitscc &assign_extver( long index, long long ver );DESCRIPTION
assign hduver() or assign extver() changes HDU version number specified by index. ver isreflected to EXTVER in a header.
The version number of Primary HDU can also be specified.
PARAMETER[I] index HDU index which designates HDU whose version number is to be changed[I] nameversion number to be set([I] : input, [O] : output)
RETURN VALUE
assign hduver () returns a reference to itself.
EXAMPLES
fits.assign_hduver(index, 101);

12.3.25

assign hdulevel(), assign extlevel()NAME
assign hdulevel() — Change a HDU level number
SYNOPSIS
fitscc &assign_hdulevel( long index, long long level );fitscc &assign_extlevel( long index, long long level );DESCRIPTION
assign hdulevel() or assign extlevel() changes HDU level number specified by index. levelis reflected to EXTLEVEL in a header. The level number of Primary HDU can also be specified.
PARAMETER[I] index HDU index which designates HDU whose level number is to be changed[I] namelevel number to be set([I] : input, [O] : output)
RETURN VALUE
assign hdulevel() returns a reference to itself.
EXAMPLES
fits.assign_hdulevel(index, 101);

Ver. 1.2.1
12.3.26

99
hduver is set(), extver is set()

NAME
hduver is set() — Check whether HDU version is set
SYNOPSIS
bool hduver_is_set( long index ) const;bool hduver_is_set( const char *hduname ) const;bool extver_is_set( long index ) const;bool extver_is_set( const char *extname ) const;
DESCRIPTION
hduver is set() or extver is set() checks whether HDU version specified by index is set ornot.
PARAMETER[I] index
HDU index[I] hduname HDU name[I] extname HDU name([I] : input, [O] : output)
RETURN VALUE
hduver is set() or extver is set() returns true if a HDU version number is set, otherwise false.
EXAMPLES
Following code checks a setting of a version number for all HDUs. If the version number is
not stated, version 100 will automatically be set.
long i;for ( i=0 ; i < fits.length() ; i++ ) {if ( fits.hduver_is_set(i) == false ) {fits.assign_hduver(i, 100);}}
12.3.27

hdulevel is set(), extlevel is set()

NAME
hdulevel is set() — Check whether HDU level is set
SYNOPSIS
bool hdulevel_is_set( long index ) const;bool hdulevel_is_set( const char *hduname ) const;bool extlevel_is_set( long index ) const;bool extlevel_is_set( const char *extname ) const;
DESCRIPTION
hdulevel is set() or extlevel is set() checks whether HDU level specified by index is set ornot.
PARAMETER[I] index
HDU index[I] hduname HDU name[I] extname HDU name([I] : input, [O] : output)

100

SFITSIO User’s Reference Guide

RETURN VALUE
hdulevel is set() or extlevel is set() returns true if a HDU level number is set, otherwise false.
EXAMPLES
Following code checks a setting of a level number for all HDUs. If the level number is notstated, level 1234 will automatically be set.
long i;for ( i=0 ; i < fits.length() ; i++ ) {if ( fits.hdulevel_is_set(i) == false ) {fits.assign_hdulevel(i, 1234);}}

Ver. 1.2.1

12.4

101

Operation of header

In this section, we describe how to handle APIs to operate a header. APIs are classified in two
groups.37) The first case is following format:¨§¥

value = fits.hdu( ... ).function( ... );And the second case is following format:¨§

value = fits.hdu( ... ).header( ... ).function( ... );value = fits.hdu( ... ).headerf( ... ).function( ... );¦¥¦To the argument in the bracket of hdu( ... ), a HDU index (long index) or a HDU name(const char *hduname) should be specified. Also, in case of an Image HDU, “hdu( ... )” partcan be used as “image( ... )”. In addition, in case of an Ascii Table HDU or Binary Table HDU,
“table( ... )” can be used.
To the argument in the bracket of “header( ... )”, specify the header index (long index) or
header keyword (const char *keyword). To the argument in the bracket of “headerf( ... )”,specify the header keyword to the same way as printf() function in libc.
For the rest of this document, since the arguments in the brackets “hdu( ... )”, “header( ... )”and “headerf( ... )” are all the same, descriptions about these arguments are omitted.
The number of header keyword is up to 54 characters and there is no limit to the string length
in the SFITSIO. (Refer §9.1.) Even if the length of a header record exceeds 80 characters, it isstored to a file appropriately.
12.4.1hdu().header length()NAME
hdu().header length() — Number of records in a header
SYNOPSIS
long hdu( ... ).header_length() const;
RETURN VALUE
hdu().header length() returns the number of records in a header.
EXAMPLES
Following code displays the number of records in a header.
fits_image &primary = fits.image("Primary");
printf("Record Count = %ld\n", primary.header_length());

12.4.2hdu().header index()NAME
hdu().header index() — Header record index in a header
SYNOPSIS
long hdu( ... ).header_index( const char *keyword ) const;
long hdu( ... ).header_index( const char *keyword, bool is_description ) const;
37)
You can use APIs for handling headers like following combinations of member functions that express exact class structures: The first case is value = fits.hdu(...).header().function(...);, and the second case isvalue = fits.hdu(...).header().at(...).function(...);. See SFITSIO header files (fits hdu.h, fits header.h,and fits header record.h) for details.

102

SFITSIO User’s Reference Guide

DESCRIPTION
hdu().header index() searches a keyword keyword from a record which format is not descriptive (unlike COMMENT or HISTORY) and returns its record index. It searches from arecord which format is descriptive if is_description is true.
It returns negative value if the keyword is not found.
PARAMETER[I] keyword[I] is_description

keywordSpecification of record to be searched (true: descriptive format,
false: other case)([I] : input, [O] : output)

RETURN VALUE
Non-negative value
Negative value::

Record index
Error (If specified keyword was not found.)

EXAMPLES
Following code displays index of the header which has keyword ”TELESCOP”.
fits_image &primary = fits.image("Primary");
printf("Record Index = %ld\n", primary.header_index("TELESCOP"));
12.4.3hdu().header regmatch()NAME
hdu().header regmatch() — Keyword search of a header
SYNOPSIS
long hdu( ... ).header_regmatch( long index, const char *keypat,
ssize_t *rpos = NULL, size_t *rlen = NULL ) const;
long hdu( ... ).header_regmatch( const char *keypat,
ssize_t *rpos = NULL, size_t *rlen = NULL ) const;
DESCRIPTION
hdu().header regmatch() searches a keyword which matches to POSIX extended regularexpression keypat from records starting with a record specified by index and returns hit
record index. If no word matches to the expression, it returns negative value. If index is not
given, Search begins from a first record.
Position of found character is returned to *rpos and length of matched string is returned to*rlen. These arguments do not need to be given.
This member function cannot search a header record of which format is descriptive (such as
COMMENT and HISTORY).
PARAMETER[I]
index
header record index to designate search start position.
[I]
keypat keyword pattern string(regular expression)[O] rposposition of found character[O] rlenlength of matched string([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value::

Record index
Error (If specified keyword was not found.)Ver. 1.2.1

103

EXAMPLES
Following code lists every records which have header keywords starting with CRVAL1 or CRVAL2
in the Primary HDU.
fits_image &primary = fits.image("Primary");
long i = 0;
while ( 0 <= (i=primary.header_regmatch(i,"^CRVAL[1-2]")) ) {printf("%s = %s\n", primary.header(i).keyword(),primary.header(i).value());
i++;}
See also the example in §5.6 in Tutorial.

12.4.4hdu().header().svalue()NAMEhdu().header().svalue() — A string value of a header (high level)
SYNOPSIS
const char *hdu( ... ).header( ... ).svalue();
DESCRIPTION
hdu().header().svalue() removes single quotations (’) and unnecessary blank charactersfrom a string value of a specified header, and then returns it.
Since return value is an address of an object’s internal buffer, it is invalid in case if object isdeleted or this member function is called again.
RETURN VALUE
hdu().header().svalue() returns the address of a string value of a header.
EXAMPLES
Following code displays the value of the record whose name is CTYPE1 in the primary HDU
header.
fits_image &primary = fits.image("Primary");
printf("CTYPE1 = %s\n", primary.header("CTYPE1").svalue());
See also the example in §5.5 in Tutorial.

12.4.5hdu().header().get svalue()NAMEhdu().header().get svalue() — Get a string value of a header (high level)
SYNOPSIS
size_t hdu( ... ).header( ... ).get_svalue( char *dest_buf, size_t buf_size ) const;

104

SFITSIO User’s Reference Guide

DESCRIPTION
hdu().header().get svalue() removes single quotations (’) and unnecessary blank characters from a string value of a specified header, and then copies it into dest_buf. The buffer
size of dest_buf is given by buf_size.
Unlike strncpy(), this member function always terminates with ’\0’ even if the buffer size
is not enough.
PARAMETER[O] dest_buf address of a string receive buffer[I]buf_size size of a string receive buffer([I] : input, [O] : output)
RETURN VALUE
Non-negative value:

Negative value:

String length which can be copied if the buffer size is enough.
(’\0’ is not included.)Error (If string was not copied because of wrong argument.)

EXAMPLES
Following code acquires the value of the record whose name is CTYPE1 in the primary HDU
header.
char dest_buf[128];
fits_image &primary = fits.image("Primary");
primary.header("CTYPE1").get_svalue(dest_buf, sizeof(dest_buf));12.4.6hdu().header().dvalue()NAMEhdu().header().dvalue() — Real value of a header (high level)
SYNOPSIS
double hdu( ... ).header( ... ).dvalue() const;
RETURN VALUE
hdu().header().dvalue() returns a real value of a specified header record.
EXAMPLES
Following code acquires the value of record whose name is CDELT1 in the primary HDU
header.
fits_image &primary = fits.image("Primary");
double value;
value = primary.header("CDELT1").dvalue();
See also the example in §5.5 in Tutorial.

Ver. 1.2.1
12.4.7105

hdu().header().lvalue(), hdu().header().llvalue()NAMEhdu().header().lvalue(), hdu().header().llvalue() — Integer value of a header (high level)
SYNOPSIS
long hdu( ... ).header( ... ).lvalue() const;
long long hdu( ... ).header( ... ).llvalue() const;
RETURN VALUE
hdu().header().lvalue() or hdu().header().llvalue() returns an integer value of a
specified header record.
EXAMPLES
See EXAMPLES in §12.4.6 or §5.5 in Tutorial.

12.4.8hdu().header().bvalue()NAMEhdu().header().bvalue() — Boolean value of a header (high level)
SYNOPSIS
bool hdu( ... ).header( ... ).bvalue() const;
RETURN VALUE
hdu().header().bvalue() returns a boolean value of a specified header record.
EXAMPLES
See EXAMPLES in §12.4.6 or §5.5 in Tutorial.

12.4.9hdu().header().assign(), hdu().header().assignf()NAME
hdu().header().assign() — Assign a string value to a header (high level)
SYNOPSIS
fits_header_record &hdu( ... ).header( ... ).assign( const char *str );fits_header_record &hdu( ... ).header( ... ).assignf( const char *format, ... );DESCRIPTION
hdu().header().asign() or hdu().header().asignf() assigns string value str to a specified header record. Give a keyword to the argument of header() in case of appending of a
new header record.
There is no limit to the string length. (Refer §9.1.) Even if the length of a header record
exceeds 80 characters, it is stored to a file appropriately.
Specify the arguments after format in the same way as printf() in libc.
List of conversion specifiers beginning with “%” in format and their functions are shown in
the following table. To output “%” itself, give “%%” as conversion specifier.

106

SFITSIO User’s Reference Guide
Conv. Spec.
hhd
hd
d
ld
lld
zd
hhu
hu
u
lu
llu
zu
hho
ho
o
lo
llo
zo
hhx, hhXhx, hXx, X
lx, lXllx, llXzx, zX
c
s

f
e, E
g, G
a, A
p
n

Description
Converts the argument to a signed decimal number
Converts the argument to a signed decimal number
Converts the argument to a signed decimal number
Converts the argument to a signed decimal number
Converts the argument to a signed decimal number
Converts the argument to a signed decimal number
Converts the argument to an unsigned decimal number
Converts the argument to an unsigned decimal number
Converts the argument to an unsigned decimal number
Converts the argument to an unsigned decimal number
Converts the argument to an unsigned decimal number
Converts the argument to an unsigned decimal number
Converts the argument to an unsigned octadecimal number
Converts the argument to an unsigned octadecimal number
Converts the argument to an unsigned octadecimal number
Converts the argument to an unsigned octadecimal number
Converts the argument to an unsigned octadecimal number
Converts the argument to an unsigned octadecimal number
Converts the argument to an unsigned hexadecimal number
Converts the argument to an unsigned hexadecimal number
Converts the argument to an unsigned hexadecimal number
Converts the argument to an unsigned hexadecimal number
Converts the argument to an unsigned hexadecimal number
Converts the argument to an unsigned hexadecimal number
Converts the argument to an integer and use the value as an
ordinal value for a character
Writes characters from the string addressed by the argument
up to a null character is encountered or the number of characters specified have been copied
Converts a float or double argument to a decimal number inthe format [-]ddd.ddd.
Converts a float or double argument to a decimal number inthe format [-]d.ddddd e[±]dd.
Picks converted result which gives less number of charactersamong %e and %f
Converts a float or double argument to a hexadecimal number in to [-]0x d.ddddd p[±]dd format
Converts the void * argument to a hexadecimal number
Save the number of characters written so far to the integer
specified by the int * argument

Type of Argument
char
short
int
long
long long
ssize tunsigned char
unsigned shortunsigned int
unsigned longunsigned long long
size t(unsigned) char
(unsigned) short(unsigned) int(unsigned) long(unsigned) long long
size t, ssize t(unsigned) char
(unsigned) short(unsigned) int(unsigned) long(unsigned) long long
size t, ssize t
int
const char*float, double
float, double
float, double
float, double
void*
int*

Ver. 1.2.1

107

In addition, by inserting the following optional conversion specifiers between “%” and theconversion specifier, more detailed format setting can be done.
sio.printf("% f...\n",x);
↑
z

}|

{

[−][+][[0]m][.][n]Option− (minus sign)+m (number of digit). (period)n (number of digit)

Description
Aligns field contents to the left instead of the
right
1234
¯¯¯¯¯¯¯¯¯¯Always precedes the result of a signed conversion with a plus sign or minus sign
Reserves at least m number of field width. If
the converted value has fewer bytes than thefield width, it will be padded with spaces on
the left. To specify zero-padding, use “0”1234¯¯¯¯¯¯¯¯¯¯Delimits a field width and number of characters or number of decimals
Number of decimals in case of “f”, A precision in case of “e”, “E”, “g” or “G”, Numberof characters in case of a string.

Examples.printf("%-6d...

.printf("%+6d...
.printf("%10d...
.printf("%010d...

.printf("%10.5f...
.printf("%10.5f...
.printf("%.15g...
.printf("%10.5s...

PARAMETER[I] strstring to be set[I] format format string[I] ...
all element data in the format([I] : input, [O] : output)
RETURN VALUE
hdu().header().assign() and hdu().header().assignf() returns a reference to relevant
fits header record.
EXCEPTION
If the API fails fails to reserve internal buffer or to convert each element data in the specified
format, it throws an exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
Following code register the header record which keyword is TELESCOP and value is HST to
the Primary HDU. This method can be used not only in case of new assignment but also for
updating value.
fits.image("Primary").header("TELESCOP").assign("HST");
See also the example in §5.5 in Tutorial.

12.4.10hdu().header().assign()

NAME
hdu().header().assign() — Assigns a boolean value to a header. (high level)

108

SFITSIO User’s Reference GuideSYNOPSIS
fits_header_record &hdu( ... ).header( ... ).assign( bool value );DESCRIPTION
hdu().header().assign() assigns boolean value value to the specified header record. Givea keyword to the argument of header() when appending of a new header record.
PARAMETER[I] value boolean value to be set([I] : input, [O] : output)
EXCEPTION
If the API fails fails to reserve or operate internal buffer, it throws an exception derived fromSLLIB (sli::err_rec exception).
RETURN VALUE
hdu().header().assign() returns a reference to relevant fits header record.
EXAMPLES
See EXAMPLES in §12.4.9 or §5.5 in Tutorial
12.4.11hdu().header().assign()

NAME
hdu().header().assign() — Assigns an integer value to a header. (high level)
SYNOPSIS
fits_header_record &hdu( ... ).header( ... ).assign( int value );fits_header_record &hdu( ... ).header( ... ).assign( long value );fits_header_record &hdu( ... ).header( ... ).assign( long long value );DESCRIPTION
hdu().header().assign() assigns integer value value to the specified header record.
Give a keyword to the argument of header() in case of appending of a new header record.
PARAMETER[I] value Integer value to be set([I] : input, [O] : output)
RETURN VALUE
hdu().header().assign() returns a reference to relevant fits header record.
EXCEPTION
If the API fails fails to reserve or operate internal buffer, it throws an exception derived fromSLLIB (sli::err_rec exception).
EXAMPLES
Following code register the header record which keyword is CCDPICNO and value is 35 to thePrimary HDU. This method can be used not only in case of assignment of a new header
record but also for updating the value.
fits.image("Primary").header("CCDPICNO").assign(35);See also the example in§5.5 Tutorial.

Ver. 1.2.1
12.4.12109
hdu().header().assign()

NAME
hdu().header().assign() — Assigns a real value to a header. (high level)
SYNOPSIS
fits_header_record &hdu( ... ).header( ... ).assign( double value, int prec = 15 );fits_header_record &hdu( ... ).header( ... ).assign( float value, int prec = 6 );DESCRIPTION
hdu().header().assign() assigns real value value to the specified header record. Numberof digit can be specified to prec. If prec is omitted, value is written to header record as
15-digit number if its type is double and as 6-digit number if its type is float.
Give a keyword to the argument of header() in case of appending of a new header record.
PARAMETER[I] value Real value to be set[I] prec
Precision (number of digit)([I] : input, [O] : output)
RETURN VALUE
hdu().header().assign() returns a reference to relevant fits header record.
EXCEPTION
If the reservation or the operation of internal buffer is failed, this API throws an exception
derived from SLLIB (sli::err_rec exception).
EXAMPLES
Following code register the header record which keyword is CDELT1 and value is -0.01 to thePrimary HDU. This way can be used in case of not only registration of a new header record
but also updating the value.
fits.image("Primary").header("CDELT1").assign(-0.01);
See also the example in §5.5 in Tutorial.
12.4.13

hdu().header().type()NAMEhdu().header().type() — Type of header record
SYNOPSIS
int hdu( ... ).header( ... ).type() const;
DESCRIPTION
hdu().header().type() checks a type of specified header record.
It returns FITS::DOUBLE_T in case of real number, FITS::LONGLONG_T in case of integer number, FITS::DOUBLECOMPLEX_T in case of complex number, FITS::BOOL_T in case of boolean
number, and FITS::STRING_T in case of others.
RETURN VALUE
FITS::DOUBLE_T
FITS::LONGLONG_T
FITS::DOUBLECOMPLEX_T
FITS::BOOL_T
FITS::STRING_T

:
:
:
:
:

In case that header record is real number.
In case that header record is integer number.
In case that header record is complex number.
In case that header record is boolean number.
In case of others.

110

SFITSIO User’s Reference Guide

EXAMPLES
Following code checks a type of header record.
switch ( fits.hdu("Primary").header("TELESCOP").type() ) {case FITS::DOUBLE_T:
printf("Record is real number type.\n");break;
case FITS::LONGLONG_T:
printf("Record is integer number type.\n");break;
case FITS::DOUBLECOMPLEX_T:
printf("Record is complex number type.\n");break;
case FITS::BOOL_T:
printf("Record is boolean type.\n");break;
case FITS::STRING_T:
printf("Record is string type.\n");break;
default:
printf("Record is unknown type.\n");break;}
12.4.14hdu().header().status()NAME
hdu().header().status() — Status of header record
SYNOPSIS
bool hdu( ... ).header( long index ).status() const;
DESCRIPTION
hdu().header().status() checks header record specified by index whether it is normal format (in the format of A = B), description format (description of COMMENT or HISTORY)or NULL format (no keyword nor value exist), and returns FITS::NORMAL_RECORD,
FITS::DESCRIPTION_RECORD or FITS::NULL_RECORD, respectively.
RETURN VALUE
FITS::NORMAL_RECORD
FITS::DESCRIPTION_RECORD
FITS::NULL_RECORD:::

In case that header record is normal format.
In case that header record is description format.
In case that header record is NULL format.

EXAMPLES
Following code checks a status of header record.
switch ( fits.hdu("Primary").header("TELESCOP").status() ) {case FITS::NORMAL_RECORD:
printf("Record is normal format.\n");break;
case FITS::DESCRIPTION_RECORD:
printf("Record is description format.\n");Ver. 1.2.1

111
break;
case FITS::NULL_RECORD:
printf("Record is NULL format.\n");break;
default:
printf("This message should not be shown.\n");break;}

12.4.15hdu().header().keyword()NAME
hdu().header().keyword() — Keyword name of a header
SYNOPSIS
const char *hdu( ... ).header( long index ).keyword() const;
DESCRIPTION
hdu().header().keyword() returns the keyword name of header record specified by index.
Since a return value is an address of an object’s internal buffer, it is invalid in case that
object is discarded or the header record is changed.
RETURN VALUE
hdu().header().keyword() returns the address of a keyword name string of header record.
EXAMPLES
Following code displays pair of the keyword and the value of the header specified by index
in the Primary HDU to the standard output.
fits_image &primary = fits.image("Primary");
printf("%s = %s\n",primary.header(index).keyword(), primary.header(index).value());
12.4.16hdu().header().get keyword()NAME
hdu().header().get keyword() — Get a keyword string of a header. (High level)
SYNOPSIS
ssize_t hdu( ... ).header( long index ).get_keyword( char *dest_buf, size_t buf_size ) const;
DESCRIPTION
hdu().header().get keyword() copies a keyword string of a header record specified byindex into dest_buf. Buffer size of dest_buf is specified by buf_size.
Unlike strncpy() in libc, this member function always terminates with ’\0’ even if thebuffer size is not enough.
PARAMETER[O] dest_buf address of receive buffer for a string[I]
buf_size size of receive buffer for a string([I] : input, [O] : output)

112

SFITSIO User’s Reference Guide

RETURN VALUE
Non-negative value:

Negative value:

String length which can be copied if the buffer size is enough.
(’\0’ is not included)
Error (If string was not copied because of wrong argument.)

EXAMPLES
Following code acquires the keyword of the header specified by index in the Primary HDU
into the prepared buffer.
char dest_buf[128];
fits_image &primary = fits.image("Primary");
primary.header(index).get_keyword(dest_buf, sizeof(dest_buf));12.4.17hdu().header().value()NAMEhdu().header().value() — A value of a header (Low level)
SYNOPSIS
const char *hdu( ... ).header( ... ).value() const;
DESCRIPTION
hdu().header().value() returns the raw value of a specified header record.
If a value from which single quotations (’) and unnecessary blank characters are removed isneeded, use hdu().header().svalue()(§12.4.4)
Since a return value is an address of an object’s internal buffer, it is invalid if the object isdiscarded or the header record is changed.
RETURN VALUE
hdu().header().value() returns an address of a string value of a header record.
EXAMPLES
See EXAMPLES in §12.4.15.
12.4.18

hdu().header().get value()NAMEhdu().header().get value() — A value of a header (Low level)
SYNOPSIS
ssize_t hdu( ... ).header( ... ).get_value( char *dest_buf, size_t buf_size ) const;
DESCRIPTION
hdu().header().get value() copies a raw value of a specified header record to dest_buf.
Buffer size of dest_buf should be given by buf_size.
If a value from which single quotations (’) and unnecessary blank characters are removed isneeded, use hdu().header().get_svalue()(§12.4.5).
Unlike strncpy() in libc, this member function always terminates with ’\0’ even if thebuffer size is not enough.

Ver. 1.2.1

113

PARAMETER[O] dest_buf Address of receive buffer for a string[I]
buf_size Size of receive buffer for a string([I] : input, [O] : output)
RETURN VALUE
Non-negative value:

Negative value:

String length which can be copied if the buffer size is enough.
(’\0’ is not included.)Error (If string was not copied because of wrong argument.)

EXAMPLES
See EXAMPLES in §12.4.16.

12.4.19

hdu().header().comment()

NAME
hdu().header().comment() — A comment of a header
SYNOPSIS
const char *hdu( ... ).header( ... ).comment() const;
DESCRIPTION
hdu().header().comment() returns a comment string of a specified header record.
Since the return value is an address of an object’s internal buffer, it is invalid in case if theobject is discarded or the header record is changed.
RETURN VALUE
hdu().header().comment() returns an address of a comment string.
EXAMPLES
See EXAMPLES in §12.4.15.

12.4.20hdu().header().get comment()

NAME
hdu().header().get comment() — Obtain a comment of a header
SYNOPSIS
ssize_t hdu( ... ).header( ... ).get_comment( char *dest_buf, size_t buf_size ) const;
DESCRIPTION
hdu().header().get comment() copies a comment string of a specified header record todest_buf. Buffer size of dest_buf should be given by buf_size.
Unlike strncpy() in libc, this member function always terminates with ’\0’ even if thebuffer size is not enough.
PARAMETER[O] dest_buf Address of receive buffer for a string[I]
buf_size Size of receive buffer for a string([I] : input, [O] : output)

114

SFITSIO User’s Reference Guide

RETURN VALUE
Non-negative value:

Negative value:

String length which can be copied if the buffer size is enough.
(’\0’ is not included.)Error (If string was not copied because of wrong argument.)

EXAMPLES
See EXAMPLES in §12.4.16.
12.4.21hdu().header().assign value()NAMEhdu().header().assign value() — Assign a string to a header. (Low level)
SYNOPSIS
fits_header_record &hdu( ... ).header( ... ).assign_value( const char *value );fits_header_record &hdu( ... ).header( ... ).assignf_value( const char *format, ... );DESCRIPTION
hdu().header().asign value() assigns raw value value to a specified header record. To
set a string for a type of header record, give an argument for value like "’ABC’". To set a
number or a boolean of header record type, give an argument for value like "256", "3.14"
or "T".
Give a keyword to the argument of header() in case of appending of a new header record.
There is no limit to the string length. (Refer §9.1.) Even if the length of a header record
exceeds 80 characters, it is stored to a file appropriately.
Arguments after format should be given as well as that of printf() in libc.
PARAMETER[I] value
A string to be set[I] format A format string[I] ...
All element data in the format([I] : input, [O] : output)
RETURN VALUE
hdu().header().asign value() returns a reference to relevant fits header record.
EXCEPTION
If the API fails fails to reserve internal buffer or to convert each element in the specified
format, it throws an exception derived from SLLIB or SFITSIO (sli::err_rec exception).
EXAMPLES
fits.hdu("Primary").header("TELESCOP").assign_value("’HST’");
12.4.22

hdu().header().assign comment()

NAME
hdu().header().assign comment() — Change a comment of a header
SYNOPSIS
fits_header_record &hdu( ... ).header( ... ).assign_comment( const char *comment );fits_header_record &hdu( ... ).header( ... ).assignf_comment( const char *format, ... );Ver. 1.2.1

115

DESCRIPTION
hdu().header().asign comment() assigns string comment to a specified header record.
Give a keyword to the argument of header() in case of appending of a new header record.
Arguments after format should be specified in the same way as printf() in libc.
PARAMETER[I] comment A string to be set[I] format
A format string[I] ...
All element data in the format([I] : input, [O] : output)
RETURN VALUE
hdu().header().asign comment() returns a reference to relevant fits header record.
EXCEPTION
If the API fails fails to reserve internal buffer or to convert each element in the specified
format, it throws an exception derived from SLLIB or SFITSIO (sli::err_rec exception).
EXAMPLES
fits.hdu("Primary").header("TELESCOP").assign("HST").assign_comment("Name of telescope");See also the example in §5.5 in Tutorial.
12.4.23

hdu().header update()NAME
hdu().header update() — Update or append a header record
SYNOPSIS
fits_hdu &hdu( ... ).header_update( const char *keyword,
const char *value, const char *comment );DESCRIPTION
hdu().header update() updates a raw value by value and a comment by comment of arecord specified by keyword. If updating is not necessary, NULL is given to value or comment.
If keyword is not found in the header, it will be appended.
To set a string of header record type, give an argument for value like "’ABC’". To set a
number or a boolean of header record type, give an argument for value like "256", "3.14"
or "T".
PARAMETER[I] keyword A keyword[I] value
A string value to be set[I] comment A comment value to be set([I] : input, [O] : output)
RETURN VALUE
hdu().header update() returns a reference to relevant fits hdu.
EXCEPTION
If the API fails fails to reserve internal buffer (for example, reservation of area for a record
to be appended is failed because of lack of memory), it throws an exception derived fromSLLIB or SFITSIO (sli::err_rec exception).

116

SFITSIO User’s Reference Guide

EXAMPLES
fits.hdu("Primary").header_update("TELESCOP", "HST", "Name of telescope");12.4.24

hdu().header assign()

NAME
hdu().header assign() — Update a header record
SYNOPSIS
fits_hdu &hdu( ... ).header_assign( long index, const fits::header_def &def );fits_hdu &hdu( ... ).header_assign( const char *header_keyword,
const fits::header_def &def );fits_hdu &hdu( ... ).header_assign( long index, const fits_header_record &obj );fits_hdu &hdu( ... ).header_assign( const char *header_keyword,
const fits_header_record &obj );fits_hdu &hdu( ... ).header_assign( long index,
const char *keyword, const char *value, const char *comment );fits_hdu &hdu( ... ).header_assign( const char *header_keyword,
const char *keyword, const char *value, const char *comment );fits_hdu &hdu( ... ).header_assign( long index,
const char *keyword, const char *description );fits_hdu &hdu( ... ).header_assign( const char *header_keyword,
const char *keyword, const char *description );DESCRIPTION
hdu().header assign() updates a header record specified by index or header_keyword toa content specified by each argument.
PARAMETER[I] index
An index of header record to be updated[I] header_keyword A keyword of header record to be updated[I] deffits::table def structure to be copied at updating[I] obj
An object to be copied at updating[I] keyword
A new keyword value[I] value
A new record value[I] comment
A new comment value[I] description
A new Description value([I] : input, [O] : output)
RETURN VALUE
hdu().header assign() returns a reference to relevant fits hdu.
EXCEPTION
If the API fails fails to operate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
Following code updates header record specified by index
fits.hdu("Primary").header_assign(index, "TELESCOP", "HST", "Name of telescope");Ver. 1.2.1
12.4.25117
hdu().header init()NAME
hdu().header init() — Initialize a header
SYNOPSIS
fits_hdu &hdu( ... ).header_init();fits_hdu &hdu( ... ).header_init( const fits::header_def defs[] );fits_hdu &hdu( ... ).header_init( const fits_header &obj );DESCRIPTION
hdu().header init() deletes the header and if defs is specified, assign that value to theheader.
Definition of fits::header_def is follows:
typedef struct {const char *keyword;
const char *value;
const char *comment;} fits::header_def;
All of last members in array defs should be NULL.
PARAMETER[I] defs Array of fits::table_def structure to be copied[I] obj
An object to be copied([I] : input, [O] : output)
RETURN VALUE
hdu().header init() returns a reference to relevant fits hdu.
EXCEPTION
If the API fails fails to manipulate internal buffer (for example, reservation of area for specified
def is failed because of lack of memory), it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits::header_def defs[] = { {"TELESCOP", "’SUBARU’", "Name of telescope"},{"OBSERVAT", "’NAOJ’", "Observatory name"},{"COMMENT", "--------------------------------"},{NULL} };fits.hdu("Primary").header_init(defs);
If the value is string, both "’SUBARU’" and "SUBARU" can be used. However, in order tostore a number like 123 into a file as a string, set the value like "’123’".
In case of description of a comment or a history, give NULL to either value or comment.
See also the example in §5.9 in Tutorial.
12.4.26

hdu().header swap()NAME
hdu().header swap() — Swap headers
SYNOPSIS
fits_hdu &hdu( ... ).header_swap( fits_header &obj );118

SFITSIO User’s Reference Guide

DESCRIPTION
hdu().header swap() swaps a FITS header object for one which specified as obj. The swap
operation is not applied for header records having properties of FITS data unit.
PARAMETER[I/O] obj an image object for swap([I] : input, [O] : output)
RETURN VALUE
hdu().header swap() returns a reference to the modified fits hdu object
EXAMPLES
The following code swaps a header of HDU “AAAA” for one of HDU “BBBB”.
fits_header &obj = fits.hdu("BBBB").header();fits.hdu("AAAA").header_swap(obj);

12.4.27

hdu().header append records()

NAME
hdu().header append records() — Append a header record
SYNOPSIS
fits_hdu &hdu( ... ).header_append_records( const fits::header_def defs[] );fits_hdu &hdu( ... ).header_append_records( const fits_header &obj );DESCRIPTION
hdu().header append records() adds contents of defs to a header. All last membersin the array of defs are set to NULL. For more information on fits::header_def, see§12.4.25(hdu().header init()).
PARAMETER[I] defs An array of fits::table_def structure to be copied[I] obj
A header object to be copied([I] : input, [O] : output)
RETURN VALUE
hdu().header append records() returns a reference to the modified fits hdu object.
EXCEPTION
If the API fails fails to manipulate the internal buffer (for example, this API cannot allocate
memory space for records to be appended due to lack of memory), it throws an exception
derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
fits::header_def defs[] = { {"TELESCOP", "’SUBARU’", "Name of telescope"},{"OBSERVAT", "’NAOJ’", "Observatory name"},{"COMMENT", "--------------------------------"},{NULL} };fits.hdu("Primary").header_append_records(defs);
See also the example in §5.7 in Tutorial.

Ver. 1.2.1
12.4.28119
hdu().header append()NAME
hdu().header append() — Append a header record
SYNOPSIS
fits_hdu &hdu( ... ).header_append( const char *keyword );fits_hdu &hdu( ... ).header_append( const char *keyword, const char *value,
const char *comment );fits_hdu &hdu( ... ).header_append( const char *keyword, const char *description );fits_hdu &hdu( ... ).header_append( const fits::header_def &def );fits_hdu &hdu( ... ).header_append( const fits_header_record &obj );DESCRIPTION
hdu().header append() appends a header record with a keyword keyword, a value value,
and a comment comment to a header. In case description was specified, this API appends
a header record in the format of COMMENT or HISTORY.
There is no limit to the string length of value and description (§9.1). Even if the lengthof a header record exceeds 80 characters, it is stored to a file appropriately.
PARAMETER[I] keyword
A keyword of a record to be appended[I] value
A value of a record to be appended[I] comment
A comment of a record to be appended[I] description A description of a record to be appended[I] deffits::table_def structure to be appended[I] obj
A header record object to be appended([I] : input, [O] : output)
RETURN VALUE
hdu().header append() returns a reference to the modified fits hdu object.
EXCEPTION
If the API fails fails to manipulate the internal buffer (for example, it cannot allocate memory
space for records to be appended due to lack of memory), it throws an exception derived
from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
fits.hdu("Primary").header_append("TELESCOP", "’SUBARU’", "Name of telescope");See also the example in §5.7 in Tutorial.

12.4.29

hdu().header insert records()

NAME
hdu().header insert records() — Insert a header record
SYNOPSIS
fits_hdu &hdu( ... ).header_insert_records( long index,
const fits::header_def defs[] );fits_hdu &hdu( ... ).header_insert_records( const char *keyword,
const fits::header_def defs[] );fits_hdu &hdu( ... ).header_insert_records( long index, const fits_header &obj );120

SFITSIO User’s Reference Guide
fits_hdu &hdu( ... ).header_insert_records( const char *keyword,
const fits_header &obj );DESCRIPTION
hdu().header insert records() inserts a contents of defs into a record specified by index
or keyword. All last members in the array of defs are set to NULL. For more information
about fits::header_def, see §12.4.25(hdu().header init()).
PARAMETER[I] index
An index of a record to be inserted[I] keyword A keyword of a record to be inserted[I] defs
An array of fits::table_def structure to be copied at the insertion[I] obj
An object to be copied at the insertion([I] : input, [O] : output)
RETURN VALUE
hdu().header insert records() returns a reference to the modified fits hdu object.
EXCEPTION
If the API fails fails to manipulate the internal buffer(for example, this API cannot allocate
memory space for records to be appended due to lack of memory), it throws an exception
derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
fits::header_def defs[] = { {"TELESCOP", "’SUBARU’", "Name of telescope"},{"OBSERVAT", "’NAOJ’", "Observatory name"},{"COMMENT", "--------------------------------"},{NULL} };long insert_index = 1;
fits.hdu("Primary").header_insert_records(insert_index, defs);
12.4.30

hdu().header insert()

NAME
hdu().header insert() — Insert a header record
SYNOPSIS
fits_hdu &hdu( ... ).header_insert( long index,
const char *keyword,
const char *value, const char *comment );fits_hdu &hdu( ... ).header_insert( const char *record_keyword,
const char *keyword,
const char *value, const char *comment );fits_hdu &hdu( ... ).header_insert( long index,
const char *keyword, const char *description );fits_hdu &hdu( ... ).header_insert( const char *record_keyword,
const char *keyword, const char *description );fits_hdu &hdu( ... ).header_insert( long index, const fits::header_def &def );fits_hdu &hdu( ... ).header_insert( const char *record_keyword,
const fits::header_def &def );fits_hdu &hdu( ... ).header_insert( long index, const fits_header_record &obj );fits_hdu &hdu( ... ).header_insert( const char *record_keyword,
const fits_header_record &obj );Ver. 1.2.1

121

DESCRIPTION
hdu().header insert() inserts a header record with a keyword keyword, a value value, anda comment comment into a record specified by index0 or keyword0. In case description
was specified, this API inserts a header record in the format of COMMENT or HISTORY.
PARAMETER[I] index
An index in header records for the insertion[I] record_keyword A keyword in header records for the insertion[I] deffits::header_def structure to be copied at the insertion[I] obj
An object to be copied at the insertion[I] keyword
A keyword to be inserted[I] value
A value to be inserted[I] comment
A comment to be inserted[I] description
A description to be inserted([I] : input, [O] : output)
RETURN VALUE
hdu().header insert() returns a reference to the modified fits hdu object.
EXCEPTION
If the API fails fails to manipulate the internal buffer (for example, this API cannot allocate
memory space for records to be appended due to lack of memory), it throws an exception
derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
long insert_index = 1;
fits.hdu("Primary").header_insert(insert_index, "TELESCOP","’SUBARU’", "Name of telescope");12.4.31

hdu().header erase records()

NAME
hdu().header erase records() — Delete header records
SYNOPSIS
fits_hdu &hdu( ... ).header_erase_records( long index, long num_records );fits_hdu &hdu( ... ).header_erase_records( const char *keyword, long num_records );DESCRIPTION
hdu().header erase records() deletes number of num records header records from a record
specified by index or keyword.
PARAMETER[I] index

An index in header records. The API deletes records starting with theindex[I] keyword
A keyword in header records. The API deletes records starting withthe keyword.
[I] num_records The number of records to be deleted.
([I] : input, [O] : output)

RETURN VALUE
hdu().header erase records() returns a reference to the modified fits hdu object

122

SFITSIO User’s Reference Guide

EXCEPTION
If the API fails fails to manipulate the internal buffer (for example, this API cannot resize memory space after deleting records), it throws an exception derived from SLLIB or
SFITSIO(sli::err_rec exception).
EXAMPLES
The following code deletes two records from a record of 0-th index in Primary HDU header.
fits.hdu("Primary").header_erase_records(0L, 2);

12.4.32

hdu().header erase()NAME
hdu().header erase() — Delete header records
SYNOPSIS
fits_hdu &hdu( ... ).header_erase( long index );fits_hdu &hdu( ... ).header_erase( const char *keyword );DESCRIPTION
hdu().header erase() deletes a header records specified by index or keyword.
PARAMETER[I] index
An index to be deleted in header records.
[I] keyword A keyword to be deleted in header records.
([I] : input, [O] : output)
RETURN VALUE
hdu().header erase() returns a reference to the modified fits hdu object.
EXCEPTION
If the API fails fails to manipulate the internal buffer (for example, this API cannot resize memory space after deleting records), it throws an exception derived from SLLIB or
SFITSIO(sli::err_rec exception).
EXAMPLES
The following code deletes a record of 0-th index in Primary HDU header.
fits.hdu("Primary").header_erase(0L);

12.4.33

hdu().header rename()NAME
hdu().header rename() — Rename a keyword of a header record
SYNOPSIS
fits_hdu &hdu( ... ).header_rename( long index0, const char *new_name );fits_hdu &hdu( ... ).header_rename( const char *keyword0, const char *new_name );DESCRIPTION
hdu().header rename() member function renames the keyword of the header record specified
by index0 or keyword0 to new name.

Ver. 1.2.1

123

PARAMETER[I] index0
An index to be renamed in header records.
[I] keyword0 A keyword to be renamed in header records.
[I] new_name A new keyword.
([I] : input, [O] : output)
RETURN VALUE
hdu().header rename() returns a reference to the modified fits hdu object.
EXCEPTION
If the API fails fails to manipulate the internal buffer, it throws an exception derived fromSLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
The following code renames the keyword “RADECSYS” in Primary HDU to “RADESYS”.
fits.hdu("Primary").header_rename("RADECSYS", "RADESYS");

12.4.34

hdu().header()NAME
hdu().header() — A reference to a header object
SYNOPSIS
fits_header &hdu( ... ).header();
RETURN VALUE
hdu().header() returns a reference to a header object.
EXAMPLES
The following code copies a reference to a header object in Primary HDU.
fits_header &primary_header = fits.hdu("Primary").header();

12.4.35

hdu().header formatted string()NAME
hdu().header formatted string() — Formatted header string
SYNOPSIS
const char *hdu( ... ).header_formatted_string();
DESCRIPTION
hdu().header formatted string() creates a formatted string in FITS file format for all
records in header in the object and returns the address. Returned result is a string of 80 × n
characters without ’\n’ but with ’\0’ termination. The CONTINUE keyword will be included
when handling long records.
This API facilitates cooperation with WCSLIB.
RETURN VALUE
hdu().header formatted string() returns an address to the formatted strings.

124

SFITSIO User’s Reference Guide

EXCEPTION
If the API fails fails to manipulate the internal buffer, it throws an exception derived fromSLLIB (sli::err_rec exception).
EXAMPLES
The following code displays the number of lines of the formatted all header records in Primary
HDU and the whole string. tstring class allows programmers to manipulate strings easily.
tstring hdr_all = fits.image("Primary").header_formatted_string();
printf("Number of Lines = %d\n", (int)hdr_all.length() / 80);
printf("Formatted header. :\n");printf("%s\n", hdr_all.cstr());
See also the example using WCSLIB in §5.13 in Tutorial.
For more information about tstring class, see APPENDIX3 (§15).

12.4.36

hdu().header().get section info()NAME
hdu().header().get section info() — Parse IRAF-style information for a rectangular area
SYNOPSIS
int hdu( ... ).header( ... ).get_section_info( long dest_buf[], int buf_len ) const;
DESCRIPTIONThis member function parses IRAF-style information for a rectangular area such as BIASSEC
keyword record, and stores the result into an array dest buf whose length is buf len.
For example, (3073,31,0,512) is stored into dest buf for the header record:
BIASSEC = ’[3074:3104,1:512] ’.
Values in dest buf can be directly given to image().stat pixels() member function (§12.6.41)
to compute pixel statistics.
PARAMETER[O] dest_buf An array for the result[I]buf_lenLength of buffer of dest_buf (should be 4)([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value::

Number of values stored in the array (should be 4)
Error (Parse failed.)

EXAMPLES
See the example code in exercise 3 in §1.1.
12.4.37

hdu().header().assign system time()NAME
hdu().header().assign system time() — Set current time in UTC
SYNOPSIS
fits_header_record &hdu( ... ).header( ... ).assign_system_time();Ver. 1.2.1

125

DESCRIPTIONThis member function sets current time (UTC) in yyyy-mm-ddThh:mm:ss format.
RETURN VALUE
hdu().assign system time() returns a reference to a header object.
EXAMPLES
Next code appends DATE keyword record, and sets current time in UTC.
fits.image("Primary").header_append("DATE").header("DATE").assign_system_time();12.4.38

hdu().header fill blank comments()NAME
hdu().header fill blank comments() — Fill blank comments using comment dictionaries
SYNOPSIS
fits_hdu &hdu( ... ).header_fill_blank_comments(int hdutype = FITS::ANY_HDU);DESCRIPTION
hdu().header fill blank comments() fills blank comments in the FITS header with contents
provided by SFITSIO built-in comment dictionaries. There are four dictionaries in SFITSIO
library that consist of dedicated dictionaries for three HDU types and a dictionary for fallback contents.
The argument hdutype takes FITS::IMAGE_HDU, FITS::BINARY_TABLE_HDU or FITS::ASCII_TABLE_HDU
to select each dedicated dictionary. If FITS::ANY_HDU is set or argument is omitted, a suitablecomment dictionary is automatically selected.
See §12.4.40 to update SFITSIO built-in comment dictionaries.
PARAMETER[I] hdutype Type of HDU([I] : input, [O] : output)
RETURN VALUE
hdu().header fill blank comments() returns a reference to the modified fits hdu object.
EXCEPTION
If the API fails fails to manipulate the internal buffer, it throws an exception derived fromSLLIB (sli::err_rec exception).
EXAMPLES
The following code fills blank comments in Primary HDU.
fits.image("Primary").header_fill_blank_comments(FITS::IMAGE_HDU);126

SFITSIO User’s Reference Guide

12.4.39

hdu().header assign default comments()NAME
hdu().header assign default comments() — Overwrite comments using comment dictionaries
SYNOPSIS
fits_hdu &hdu( ... ).header_assign_default_comments(int hdutype = FITS::ANY_HDU);DESCRIPTION
hdu().header assign default comments() overwrites comments in the FITS header with contents provided by SFITSIO built-in comment dictionaries. There are four dictionaries in
SFITSIO library that consist of dedicated dictionaries for three HDU types and a dictionary
for fall-back contents.
The argument hdutype takes FITS::IMAGE_HDU, FITS::BINARY_TABLE_HDU or FITS::ASCII_TABLE_HDU
to select each dedicated dictionary. If FITS::ANY_HDU is set or argument is omitted, a suitablecomment dictionary is automatically selected.
See §12.4.40 to update SFITSIO built-in comment dictionaries.
PARAMETER[I] hdutype Type of HDU([I] : input, [O] : output)
RETURN VALUE
hdu().header assign default comments() returns a reference to the modified fits hdu object.
EXCEPTION
If the API fails fails to manipulate the internal buffer, it throws an exception derived fromSLLIB (sli::err_rec exception).
EXAMPLES
The following code overwrites comments in Primary HDU.
fits.image("Primary").header_assign_default_comments(FITS::IMAGE_HDU);
12.4.40

fits::update comment dictionary()NAME
fits::update comment dictionary() — Update comment dictionaries
SYNOPSIS#include <sli/fits_header_record.h>
const asarray_tstring &update_comment_dictionary( int hdutype,
const char *const *new_kwd_comments );DESCRIPTIONThis function updates contents of SFITSIO built-in comment dictionaries. There are four dictionaries in SFITSIO library that consist of dedicated dictionaries for three HDU types and adictionary for fall-back contents. The dictionaries are used in hdu().header fill blank comments(),
hdu().header assign default comments() member functions. See also §12.4.38 and §12.4.39.
The argument hdutype takes FITS::IMAGE_HDU, FITS::BINARY_TABLE_HDU, FITS::ASCII_TABLE_HDU
or FITS::ANY_HDU for each dictionary to be updated.
The argument new_kwd_comments takes pointer array of strings including keywords andcomments such as keyword1, comment1, keyword2, comment2, ... , NULL.

Ver. 1.2.1
PARAMETER[I] hdutype[I] new_kwd_comments([I] : input, [O] : output)

127

Type of HDU
Pointer array of strings having keywords and comments

RETURN VALUEThis function returns read-only reference of asarray tstring object having updated comment
dictionary.
EXCEPTION
If the API fails fails to manipulate the internal buffer, it throws an exception derived fromSLLIB (sli::err_rec exception).
EXAMPLESThis code updates general comment dictionary and that for binary table HDU.
#include <sli/fits_header_record.h>/* comment strings for blank comment in template */static const char *Kwd_comment_any[] = {/*|MIN"TIME-EPH", "epoch time for FITS header","SMPLBASE", "base telemetry referred to shrink rows",
/*
|MIN
NULL
};
static const char *Kwd_comment_bintable[] = {/*|MIN"TTNAM#","original telemetry name","TCONV#","type of data conversion","TSTAT#","definition of status values","TINPL#","type of interpolation","TSPAN#","[s] maximum span for interpolation","", "",
/*
|MIN
NULL
};

MAX| */

MAX| */

MAX| */

MAX| */

int main(){/* update comment dictionaries */fits::update_comment_dictionary(FITS::ANY_HDU, Kwd_comment_any);
fits::update_comment_dictionary(FITS::BINARY_TABLE_HDU, Kwd_comment_bintable);

128

SFITSIO User’s Reference Guide

12.5

Operation of header (low-level) and disk-based FITS I/Ofits header class has some member functions to read/write FITS header unit and to skip FITS
data unit for an opened stream. These member functions enable high-speed access of FITS header
and flexible data access of FITS data unit using APIs provided by SLLIB stream classes.
The SFITSIO software package contains “tools/hv.cc” that reads FITS header with highspeed file access. Refer hv.cc as an example code that uses APIs in this section.
12.5.1fits header::read stream()

NAME
fits header::read stream() — Read a FITS header unit only
SYNOPSIS
ssize_t fits_header::read_stream( cstreamio &sref );DESCRIPTIONThis member function reads and parses a FITS header unit from an opened stream (sref),and stores the contents of it into the object.
After calling this member function, the position indicator of stream will be set to the beginning of succeeding FITS data unit.
First argument sref takes a reference to object of inherited class of cstreamio class. See
APPENDIX and manual of SLLIB for details of these classes for stream handling.
PARAMETER[I] sref Reference to object that manages opened stream([I] : input, [O] : output)
RETURN VALUE
Positive value
0
Negative value

12.5.2:::Byte length of input stream.
EOF of input stream.
Error.

fits header::write stream()

NAME
fits header::write stream() — Output a FITS header unit only
SYNOPSIS
ssize_t fits_header::write_stream( cstreamio &sref, bool end_and_blank );DESCRIPTIONThis member function outputs formatted FITS header (80-characters width) to an opened
stream (sref).
When the argument end and blank is true, written result contains END keyword andpadding of white space for 2880 bytes block, therefore, programmer’s code can output succeeding FITS data unit using the same stream.
END keyword and padding are not written when end and blank is false.
First argument sref takes a reference to object of inherited class of cstreamio class. See
APPENDIX and manual of SLLIB for details of these classes for stream handling.

Ver. 1.2.1

129

PARAMETER[I] sref
Reference to object that manages opened stream[I] end_and_blank END keyword and padding are written or not([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value

12.5.3::

Byte length of output stream.
Error.

fits header::skip data stream()

NAME
fits header::skip data stream() — Skip a FITS data unit
SYNOPSIS
ssize_t fits_header::skip_data_stream( cstreamio &sref );DESCRIPTIONThis member function skips the byte data of a FITS data unit using header informationin the object. Before using this member function, programmers have to use read stream()
member function (§12.5.1) to give the object the header information.
The position indicator of stream will be set to the beginning of succeeding FITS header unit
when the next HDU exists. To know the existence of next HDU, test the return value ofread stream() member function (§12.5.1).
First argument sref takes a reference to object of inherited class of cstreamio class. See
APPENDIX and manual of SLLIB for details of these classes for stream handling.
PARAMETER[I] sref Reference to object that manages opened stream([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value::

Byte length of input stream.
Error.

130

SFITSIO User’s Reference Guide

12.6

APIs for manipulation of an Image HDU

In this section, we describe APIs to manipulate an Image HDU. Every argument of “image( ... )”of all APIs in this section is the HDU index (long index) or the HDU name (const char *hduname),
so we omit the description of this argument.
12.6.1

image().hduname(), image().assign hduname()

NAME
image().assign hduname(), image().hduname() — Manipulation of an Image HDU name
SYNOPSIS
const char *image( ... ).hduname();const char *image( ... ).extname();fits_image &image( ... ).assign_hduname( const char *name );fits_image &image( ... ).assign_extname( const char *name );DESCRIPTION
image().hduname() returns a HDU name.
image().assign hduname() assigns a HDU name. The argument name is reflected to EXTNAMEof the header. This API can also be used for Primary HDU.
PARAMETER[I] name a HDU name to be set([I] : input, [O] : output)
RETURN VALUE
image().hduname() returns a pointer to a string of HDU name.
image().assign_hduname() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, a failure of memory allocation for modifying HDU name), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
printf("HDU name=%s\n", fits.image("Primary").hduname());
12.6.2

image().hduver(), image().assign hduver()

NAME
image().assign hduver(), image().hduver() — Manipulation of an Image HDU version number
SYNOPSIS
long long image( ... ).hduver();long long image( ... ).extver();fits_image &image( ... ).assign_hduver( long long ver );fits_image &image( ... ).assign_extver( long long ver );DESCRIPTION
image().hduver() returns a HDU version number.
image().assign hduver() sets a HDU version number. The argument ver is reflected to
EXTVER of the header. This API can also be used for Primary HDU.

Ver. 1.2.1

131

PARAMETER[I] ver a version number to be set([I] : input, [O] : output)
RETURN VALUE
image().hduver() returns a HDU version number.
image().assign_hduver() returns a reference to the modified fits image object.
EXAMPLES
printf("HDU version=%lld\n", fits.image("Primary").hduver());
12.6.3

image().dim length()

NAME
image().dim length() — The number of axes
SYNOPSIS
long image( ... ).dim_length() const;
long image( ... ).axis_length() const;
RETURN VALUE
image().dim length() returns the number of axes.
EXAMPLES
printf("The number of dimensions=%ld\n", fits.image("Primary").dim_length());
12.6.4

image().length()

NAME
image().length() — The number of pixels
SYNOPSIS
long image( ... ).length() const;
long image( ... ).length( long axis ) const;
DESCRIPTION
image().length() returns the number of pixels in axis. When axis is not specified, thetotal number of pixels is returned.
PARAMETER[I] axis axis whose number of pixels is returned([I] : input, [O] : output)
RETURN VALUE
image().length() returns the number of pixels
EXAMPLES
The following code displays the total number of pixels and the number of pixels in each axisof ImageHDU.
long axis;
printf("the total number of pixels=%ld\n", fits.image("Primary").length());
for ( axis = 0 ; axis < fits.image("Primary").dim_length() ; axis++ ) {132

SFITSIO User’s Reference Guide
printf("axis[%ld] the number of pixels[%ld]\n",axis, fits.image("Primary").length(axis));}12.6.5

image().type()

NAME
image().type() — A data type of pixel values
SYNOPSIS
int image( ... ).type() const;
RETURN VALUE
image().type() returns a data type of pixel values. They are any one of “ FITS::DOUBLE_T,
FITS::FLOAT_T, FITS::LONGLONG_T, FITS::LONG_T, FITS::SHORT_T, or FITS::BYTE_T ”.
EXAMPLES
The following code displays a data type of pixel values.
switch ( fits.image("Primary").type() ) {case FITS::DOUBLE_T:
printf("Data type: DOUBLE\n");break;
case FITS::FLOAT_T:
printf("Data type: FLOAT\n");break;
case FITS::LONGLONG_T:
printf("Data type: LONGLONG\n");break;
case FITS::LONG_T:
printf("Data type: LONG\n");break;
case FITS::SHORT_T:
printf("Data type: SHORT\n");break;
case FITS::BYTE_T:
printf("Data type: BYTE\n");break;
default:
printf("Invalid data type.\n");break;}

12.6.6

image().bytes()

NAME
image().bytes() — A size of one pixel in bytes
SYNOPSIS
long image( ... ).bytes() const;

Ver. 1.2.1

133

RETURN VALUE
image().bytes() returns a size of one pixel in bytes.
EXAMPLES
printf("The size of one pixel is %ld.\n", fits.image("Primary").bytes());

12.6.7

image().col length()

NAME
image().col length() — The number of pixels in a column(x-axis)
SYNOPSIS
long image( ... ).col_length() const;
RETURN VALUE
image().col length() returns the number of pixels in a column(axis0; x-axis).
EXAMPLES
printf("The number of pixels in x-axis is %ld.\n",fits.image("Primary").col_length());

12.6.8

image().row length()

NAME
image().row length() — The number of pixels in a row(y-axis)
SYNOPSIS
long image( ... ).row_length() const;
RETURN VALUE
image().row length() returns the number of pixels in a row(axis1; y-axis).
EXAMPLES
printf("The number of pixels in y-axis is %ld.\n",fits.image("Primary").row_length());

12.6.9image().layer length()

NAME
image().layer length() — The number of pixels in a layer(z-axis)
SYNOPSIS
long image( ... ).layer_length() const;
RETURN VALUE
image().layer length() returns the number of pixels in a layer(z-axis). If the number ofdimensions is over 3, the ones of axis2 or later are returned.
EXAMPLES
printf("The number of pixels in z-axis or later is %ld.\n",fits.image("Primary").layer_length());

134

SFITSIO User’s Reference Guide

12.6.10

image().dvalue()

NAME
image().dvalue() — A pixel value in double precision
SYNOPSIS
double image( ... ).dvalue( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
double image( ... ).dvalue_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
double image( ... ).va_dvalue_v( long num_axisx, long axis0, long axis1, long axis2,
va_list ap ) const;
DESCRIPTION
image().dvalue() returns a double precision pixel value at the axis0-th column, the axis1th row, and the axis2-th layer. The value is subject to BZERO, BSCALE, and BLANK in a header.
When the value corresponded to BLANK value or the argument value is out of range, NAN
is returned.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data depending on the number of arguments. In
EXAMPLES below, n-dimensional data is treated as 1-dimensional one.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().dvalue() returns a pixel value.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO (sli::err_rec exception).
EXAMPLES
The following code sums up all pixel values.
double sum = 0;
for ( i=0 ; i < fits.image("Primary").length() ; i++ ) {sum += fits.image("Primary").dvalue(i);}See also a sample code in §5.8.

Ver. 1.2.1
12.6.11

135
image().lvalue(), image().llvalue()

NAME
image().lvalue(), image().llvalue() — A pixel value in integer
SYNOPSIS
long image( ... ).lvalue( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
long image( ... ).lvalue_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
long image( ... ).va_lvalue_v( long num_axisx, long axis0, long axis1, long axis2,
va_list ap ) const;
long long image( ... ).llvalue( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
long long image( ... ).llvalue_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
long long image( ... ).va_llvalue_v( long num_axisx,
long axis0, long axis1, long axis2,
va_list ap ) const;
DESCRIPTIONThis API returns an integer pixel value at the axis0-th column, the axis1-th row, and theaxis2-th layer. The value is subject to BZERO, BSCALE, and BLANK in a header. When thevalue corresponded to BLANK value or the argument value is out of range, INDEF LONG or
INDEF LLONG is returned.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUEThis API returns a pixel value.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO (sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.6.10 and also a sample code in §5.8.
12.6.12

image().assign()

NAME
image().assign() — Assign pixel number

136

SFITSIO User’s Reference GuideSYNOPSIS
fits_image &image( ... ).assign( double value, long axis0,
long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );fits_image &image( ... ).assign_v( double value, long num_axisx,
long axis0, long axis1, long axis2, ... );fits_image &image( ... ).va_assign_v( double value, long num_axisx,
long axis0, long axis1, long axis2,
va_list ap );DESCRIPTION
image().assign() modifies a pixel value at the axis0-th column, the axis1-th row, andthe axis2-th layer. In this modification, the value which is reflected by BZERO and BSCALE
in a header is used in order to update a pixel value in internal buffer. When value is NAN
and BLANK value is already defined, BLANK value is assigned to internal buffer. When no
BLANK value is defined at integer type, a value INDEF UCHAR, INDEF INT16, INDEF INT32
or INDEF INT64 is stored in internal buffer.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] value
a value to be set[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().assign() returns a reference to the modified fits image object.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO (sli::err_rec exception).
EXAMPLES
The following code assigns 0 to all pixel values in 0-th row.
double value = 0;
for ( i=0 ; i < fits.image("Primary").col_length() ; i++ ) {fits.image("Primary").assign(value, i,0);}
See also a sample code in §5.8.

12.6.13

image().convert type()

NAME
image().convert type() — Conversion of data typeVer. 1.2.1

137

SYNOPSIS
fits_image &image( ... ).convert_type( int new_type );fits_image &image( ... ).convert_type( int new_type, double new_zero );fits_image &image( ... ).convert_type( int new_type, double new_zero,double new_scale );fits_image &image( ... ).convert_type( int new_type, double new_zero,double new_scale, long long new_blank );DESCRIPTION
image().convert type() converts a data type of the image into new_type. A size of internalbuffer is changed if necessary. A value which can be specified as new_type is any one of“FITS::DOUBLE_T, FITS::FLOAT_T, FITS::LONGLONG_T, FITS::LONG_T, FITS::SHORT_T, or
FITS::BYTE_T”. When new_zero, new_scale, new_blank are specified, this API updates
BZERO, BSCALE and BLANK in a header and changes the image data reflected by those values.
new_blank is valid only when new_type is integer type.
PARAMETER[I] new_typea new data type for conversion[I] new_zeroa new BZERO value for conversion[I] new_scale a new BSCALE value for conversion[I] new_blank a new BLANK value for conversion([I] : input, [O] : output)
RETURN VALUE
image().convert type() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, an increase of image data size
after the conversion), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
The following code converts any type of image data in primary HDU into double.
fits.image("Primary").convert_type(FITS::DOUBLE_T);
See also a sample code in §5.11.

12.6.14

image().bzero(), image().assign bzero()

NAME
image().bzero(), image().assign bzero() — Manipulation of a zero-pointSYNOPSIS
double image( ... ).bzero() const;bool image( ... ).bzero_is_set() const;
fits_image &image( ... ).assign_bzero( double zero, int prec = 15 );fits_image &image( ... ).erase_bzero();DESCRIPTION
image().bzero() returns a value of BZERO in a header. image().bzero is set() returns
whether BZERO exists or not in a header.

138

SFITSIO User’s Reference Guide
image().assign bzero() sets a value of BZERO in the header. The number of digit precision
can be specified in prec. When this is skipped, 15 digit precsion will be inserted.
image().erase bzero() deletes a value of BZERO in the header.
These APIs do not change an actual zero-point of the image. image().convert_type() (see§12.6.13) changes both the zero-point and the image.

PARAMETER[I] zero BZERO value to be set[I] prec the number of digits precision([I] : input, [O] : output)
RETURN VALUEThis API returns a reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, image().assign bzero() cannot reallocate an address table), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
The following code checks an existence of BZERO and sets a value if it is not defined.
if ( fits.image("Primary").bzero_is_set() == false ) {fits.image("Primary").assign_bzero(0.0);}

12.6.15

image().bscale(), image().assign bscale()

NAME
image().bscale(), image().assign bscale() — Manipulation of a scaling factor
SYNOPSIS
double image( ... ).bscale() const;bool image( ... ).bscale_is_set() const;
fits_image &image( ... ).assign_bscale( double scale, int prec = 15 );fits_image &image( ... ).erase_bscale();DESCRIPTION
image().bscale() returns a value of BSCALE in a header. image().bscale is set() returns
whether BSCALE exists or not in a header.
image().assign bscale() sets a value of BSCALE in a header. The number of digit precision
can be specified in prec. When this is skipped, 15 digit precsion will be inserted.
image().erase bscale() deletes a value of BSCALE in a header.
These APIs do not change the actual scaling factor of the image. image().convert_type()(see §12.6.13) changes both the scaling factor and the image.
PARAMETER[I] scale BSCALE value to be set[I] precthe number of digit precision([I] : input, [O] : output)

Ver. 1.2.1

139

RETURN VALUEThis API returns the reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate the internal buffer (for example, image().assign bscale() cannot reallocate an address table), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
The following code checks an existence of BSCALE and sets a value if it is not defined.
if ( fits.image("Primary").bscale_is_set() == false ) {fits.image("Primary").assign_bscale(1.0);}

12.6.16

image().blank(), image().assign blank()

NAME
image().blank() — Manipulation of blank value
SYNOPSIS
long long image( ... ).blank() const;bool image( ... ).blank_is_set() const;
fits_image &image( ... ).assign_blank( long long blank );fits_image &image( ... ).erase_blank();
DESCRIPTION
image().blank() returns a value of BLANK in the header. image().blank is set() returns
whether BLANK exists or not in a header.
image().assign blank() assigns a value of BLANK in a header. image().erase blank()
erases a value of BLANK in a header.
PARAMETER[I] blank a BLANK value to be set([I] : input, [O] : output)
RETURN VALUEThis API returns a reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, image().assign blank() cannot reallocate an address table), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
The following code checks an existence of BLANK and sets a value if it is not defined.
if ( fits.image("Primary").blank_is_set() == false ) {fits.image("Primary").assign_blank(0);}140

SFITSIO User’s Reference Guide

12.6.17

image().bunit(), image().assign bunit()

NAME
image().bunit(), image().assign bunit() — manipulation of a physical unit
SYNOPSIS
const char *image( ... ).bunit();bool image( ... ).bunit_is_set();fits_image &image( ... ).assign_bunit( const char *unit );fits_image &image( ... ).erase_bunit();DESCRIPTION
image().bunit() returns the value of BUNIT(the string which represents a physical unit) ina header. The value is the address of a buffer in the object, and it is invalid when the object
is revoked or the value of BUNIT is changed.
image().bunit is set() returns whether BUNIT exists or not in a header.
image().assign bunit() sets a value of BUNIT(a physical unit) in a header. image().erase bunit()
deletes a value of BUNIT in a header.
PARAMETER[I] unit a pointer to a string of BUNIT([I] : input, [O] : output)
RETURN VALUEThis API returns a reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, image().assign bunit() cannot reallocate an address table), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
The following code checks an existence of BUNIT and sets a value if it is not defined.
if ( fits.image("Primary").bunit_is_set() == false ) {fits.image("Primary").assign_bunit("ADU");}
12.6.18

image().init()

NAME
image().init() — Initialization of an image and a header
SYNOPSIS
fits_image &image( ... ).init();fits_image &image( ... ).init( const fits_image &obj );fits_image &image( ... ).init( int type,long naxis0, long naxis1 = 0, long naxis2 = 0 );fits_image &image( ... ).init( int type, long naxis, long naxisx[] );DESCRIPTION
image().init() initializes an image and a header. Wjen obj is specified, it is copied to the
new HDU object.

Ver. 1.2.1

141

An image data type which can be specified as type is any one of “FITS::DOUBLE_T, FITS::FLOAT_T,
FITS::LONGLONG_T, FITS::LONG_T, FITS::SHORT_T, or FITS::BYTE_T”.
naxis0, naxis1, and naxis2 are the size of the image and the number of layers.
Neither EXTNAME nor EXTVER is changed.
PARAMETER[I] objan Image object copied to new one in initialization[I] type
a data type of an image[I] naxis0 the number of pixels in a column(x-axis)[I] naxis1 the number of pixels in a row(y-axis)[I] naxis2 the number of pixels in a layer(z-axis)[I] naxis
the number of lists specified by an argument naxisx[I] naxisx a list of the number of pixel in each axis([I] : input, [O] : output)
RETURN VALUE
image().init() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, a size of initialized image data
exceeds memory space available), it throws an exception derived from SLLIB or SFITSIO(sli::err_rec exception).
EXAMPLES
The following code initializes an Primary HDU with double data type, 100 pixels in x-axis,
200 pixels in y-axis, and 3 pixels in z-axis.
fits.image("Primary").init(FITS::DOUBLE_T, 100, 200, 3);
12.6.19

image().swap()

NAME
image().swap() — Image swap
SYNOPSIS
fits_image &image( ... ).swap( fits_image &obj );DESCRIPTION
image().swap() swaps an image object for one which specified as obj.
PARAMETER[I/O] obj an image object for swap([I] : input, [O] : output)
RETURN VALUE
image().swap() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits1.image("Primary").swap( fits2.image("Primary") );See also a sample code in §5.10.

142
12.6.20SFITSIO User’s Reference Guide
image().increase dim()

NAME
image().increase dim() — An axis increment
SYNOPSIS
fits_image &image( ... ).increase_dim();fits_image &image( ... ).increase_axis();DESCRIPTION
image().increase dim() increments axes by one. The initial number of pixels of an added
axis is 1. This number can be resized by image().resize().
RETURN VALUE
image().increase dim() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SFITSIO(sli::err_rec exception).
EXAMPLES
fits.image("Primary").increase_dim();12.6.21

image().decrease dim()

NAME
image().decrease dim() — An axis decrement
SYNOPSIS
fits_image &image( ... ).decrease_dim();fits_image &image( ... ).decrease_axis();DESCRIPTION
When the number of pixels in a last dimension axis is not 1, it decreases a size of internalbuffer simultaneously.
RETURN VALUE
image().decrease dim() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to allocate internal memory, it throws an exception derived from SFITSIO(sli::err_rec exception).
EXAMPLES
fits.image("Primary").decrease_dim();12.6.22

image().resize()

NAME
image().resize() — Modification of the number of pixels
SYNOPSIS
fits_image &image( ... ).resize( long axis, long size );Ver. 1.2.1

143

DESCRIPTION
image().resize() changes the number of pixels in axis to size. When the number ofpixels is increased, the additional pixels are initialized by a zero value which is reflected by
the values of BZERO and BSCALE in the header.
PARAMETER[I] axis an axis for modification[I] size the number of pixels to be set([I] : input, [O] : output)
RETURN VALUE
image().resize() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to allocate internal memory, it throws an exception derived from SFITSIO(sli::err_rec exception).
EXAMPLES
printf("before: the number of pixels=%ld\n",fits.image("Primary").col_length());
fits.image("Primary").resize(0, 2000);
printf("after: the number of pixels=%ld\n",fits.image("Primary").col_length());
12.6.23

image().assign default()

NAME
image().assign default() — Specify a value to be set for new pixels when resizing the imageSYNOPSIS
fits_image &image( ... ).assign_default( double value );fits_image &image( ... ).assign_default_value( const void *value_ptr );DESCRIPTION
Using these member functions, programmers can specify a value to be set for new pixels
created by .resize(), etc.
.assign default() is a high-level API, and the value of argument is converted into theappropriate value which is reflected by the values of BZERO, BSCALE and BLANK in the header.
Set NAN to the argument to specify BLANK value.
.assign default value() is a low-level API, and values of BZERO, etc. are not referred.
Programmers should set an address of a value whose type is that of image of current object.
PARAMETER[I] value
a value to be set for new pixels[I] value_ptr an address of a value to be set for new pixels([I] : input, [O] : output)
RETURN VALUE
These member functions returns a reference to the modified fits image object.
EXCEPTION
If the API fails to allocate internal memory, it throws an exception derived from SLLIB(sli::err_rec
exception).

144

SFITSIO User’s Reference Guide

EXAMPLES
Next code specifies BLANK value to be set for new pixels, and resizes the width of the image.
fits.image("Primary").assign_default(NAN).resize(0, 2000);

12.6.24

image().fix rect args()

NAME
image().fix rect args() — Text and fix values of arguments expressing a rectangular area
SYNOPSIS
int image( ... ).fix_rect_args( long *r_col_index, long *r_col_size,
long *r_row_index, long *r_row_size,
long *r_layer_index, long *r_layer_size ) const;
DESCRIPTION
image().fix_rect_args() tests whether the values of arguments indicate a rectangulararea inside of the image of the object. If the values indicate areas outside of the image,
image().fix_rect_args() fix the values.
Before calling .scan_cols(), etc., exact position and width can be obtained by using thismember function. When programmer’s work buffer has to be allocated, exact buffer length
can be calculated. See also §12.6.25, etc.
PARAMETER[I/O] r_col_index[I/O] r_col_size[I/O] r_row_index[I/O] r_row_size[I/O] r_layer_index[I/O] r_layer_size([I] : input, [O] : output)

pointer of a pixel index of a column(x-axis)
pointer of an offset pixels from *r col index
pointer of a pixel index of a row(y-axis)
pointer of an offset pixels from *r row index
pointer of a pixel index of a layer(z-axis)
pointer of an offset pixels from *r layer index

RETURN VALUE
0: values of arguments indicate an area inside of the image of the object.
positive : values of arguments indicate both areas inside/outside of the image of theobject.
negative : values of arguments indicate an invalid area.

12.6.25

image().scan cols()

NAME
image().scan cols() — Horizontally scans the specified area using a user-defined function
SYNOPSIS
long image( ... ).scan_cols(
long (*func)(double [],long, long,long,long,const fits_image *,void *),void *user_ptr,
long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL ) const;

Ver. 1.2.1

145

DESCRIPTION
image().scan cols() scans the rectangular area horizontally specified by third or later
arguments with following steps:
1. Allocate a temporary buffer of double type whose length is enough for one line of
specified rectangular area.
2. Pixel values in a line are converted into that of double type, and are stored into temporary buffer. In this conversion, SCALE, ZERO and BLANK are also applied.
3. User’s function func is called.
4. Repeat 2. and 3. for all lines in the rectangular area.
The user’s function has to have a loop to scan all pixel data in the temporary buffer, andshould return the number of valid pixels.
Specifications of arguments in the user-defined function (*func) are as below:
double pix[] ... temporary buffer having pixel values of a line
long n_pix ... number of pix
long axis0 ... a coordinate of x-axis
long axis1 ... a coordinate of y-axis
long axis2 ... a coordinate of z-axis
fits_image *thisp ... a pointer to this object
void *ptr ... a pointer to user_ptr
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are scanned.
user_ptr is a pointer which a user can use freely, and it is given to a last argument of auser-defined function.
Do not use a constant FITS::ALL explicitly.
PARAMETER[I] func
a pointer to a user-defined function[I] user_ptr
an arbitrary pointer which is given to a user-defined function[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
an offset pixels from layer index([I] : input, [O] : output)
RETURN VALUE
nonnegative :negative:

total number of valid pixels (returned by user’s function)
error (e.g. invalid arguments are specified)

EXAMPLES
The following code scans the image of Primary HDU, and obtains the sum of all pixel values
in res.sum and the number of valid pixels in res.npix.
struct pixels_results {double sum;long npix;
};

146

SFITSIO User’s Reference Guide

static long pixels_sum( double vals[],long n, long ii,long jj,long kk,
const fits_image *this_p, void *_p ){struct pixels_results *resp = (struct pixels_results *)_p;long i, cnt = 0;
for ( i=0 ; i < n ; i++ ) {if ( isfinite(vals[i]) ) {resp->sum += vals[i];cnt ++;}}
return cnt;}
int main(){struct pixels_results res;:res.npix = fits.image("Primary").scan_cols( &pixels_sum, (void *)&res );12.6.26

image().scan rows()

NAME
image().scan rows() — Vertically scans the specified area using a user-defined function
SYNOPSIS
long image( ... ).scan_rows(
long (*func)(double [],long, long,long,long,const fits_image *,void *),void *user_ptr,
long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL ) const;
DESCRIPTION
image().scan rows() scans the rectangular area vertically specified by third or later arguments with following steps:
1. Allocate a temporary buffer of double type whose length is enough for one column ofpixels in specified rectangular area.
2. Pixel values in a column are converted into that of double type, and are stored into
temporary buffer. In this conversion, SCALE, ZERO and BLANK are also applied.
3. User’s function func is called.
4. Repeat 2. and 3. for all columns in the rectangular area.
The user’s function has to have a loop to scan all pixel data in the temporary buffer, andshould return the number of valid pixels.
Specifications of arguments in the user-defined function (*func) are as below:
double pix[] ... temporary buffer having pixel values of a column
long n_pix ... number of pix

Ver. 1.2.1

147

long axis0 ... a coordinate of x-axis
long axis1 ... a coordinate of y-axis
long axis2 ... a coordinate of z-axis
fits_image *thisp ... a pointer to this object
void *ptr ... a pointer to user_ptr
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are scanned.
user_ptr is a pointer which a user can use freely, and it is given to a last argument of auser-defined function.
Do not use a constant FITS::ALL explicitly.
PARAMETER[I] func
a pointer to a user-defined function[I] user_ptr
an arbitrary pointer which is given to a user-defined function[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
an offset pixels from layer index([I] : input, [O] : output)
RETURN VALUE
nonnegative :negative:

total number of valid pixels (returned by user’s function)
error (e.g. invalid arguments are specified)

EXAMPLES
See EXAMPLES in §12.6.25.
12.6.27

image().scan layers()

NAME
image().scan layers() — Scan the specified rectangular area along z-axis using a user-defined
function
SYNOPSIS
long image( ... ).scan_layers(long (*func)(double [],long,long, long,long,long,const fits_image *,void *),void *user_ptr,
long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL ) const;
DESCRIPTION
image().scan layers() scans the rectangular area along z-axis specified by third or later
arguments with following steps:
1. Allocate a temporary buffer of double type whose length is enough for z-length × xlength of pixels in specified rectangular area.
2. Pixel values are converted into that of double type, and are stored into temporary buffer.
In this conversion, SCALE, ZERO and BLANK are also applied.

148

SFITSIO User’s Reference Guide
3. User’s function func is called.
4. Repeat 2. and 3. for all rows in the rectangular area.
The user’s function has to have two loops (inner loop should be for scanning z) to scan all
pixel data in the temporary buffer, and should return the number of valid pixels.
Specifications of arguments in the user-defined function (*func) are as below:
double pix[] ... temporary buffer having pixel values of z-axis × x-axis
long n_zpix ... number of pix along z-axis
long n_xpix ... number of pix along x-axis
long axis0 ... a coordinate of x-axis
long axis1 ... a coordinate of y-axis
long axis2 ... a coordinate of z-axis
fits_image *thisp ... a pointer to this object
void *ptr ... a pointer to user_ptr
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are scanned.
user_ptr is a pointer which a user can use freely, and it is given to a last argument of auser-defined function.
Do not use a constant FITS::ALL explicitly.

PARAMETER[I] func
a pointer to a user-defined function[I] user_ptr
an arbitrary pointer which is given to a user-defined function[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
an offset pixels from layer index([I] : input, [O] : output)
RETURN VALUE
nonnegative :negative:

total number of valid pixels (returned by user’s function)
error (e.g. invalid arguments are specified)

EXAMPLES
Next code obtains sum of all pixels along z-axis in each (x, y) of image in the Primary HDU,
and stores the result into prepared buffer.
static long combine_sum( double pix[], long nz, long nx,
long x, long y, long z,
const fits_image *this_p, void *_out_buf_p ){double **out_buf_p = (double **)_out_buf_p;
double *out_buf = *out_buf_p;
double v;
long i,j, nz_valid, nx_valid = 0, ix = 0;
for ( i=0 ; i < nx ; i++ ) {/* loop for X */v = 0;
nz_valid = 0;

Ver. 1.2.1

149
for ( j=0 ; j < nz ; j++ ) {if ( isfinite(pix[ix]) ) {v += pix[ix];nz_valid ++;}ix ++;}
if ( 0 < nz_valid ) {out_buf[i] = v;
nx_valid ++;}else out_buf[i] = NAN;}
*out_buf_p = out_buf + nx;
return nx_valid;/* loop for Z *//* if valid *//* count always *//* save the result *//* set next position */}int main(){double *buf;:(allocate memory on buf):
double *t_buf = buf;
res.npix = fits.image("Primary").scan_layers( &combine_sum,(void *)(&t_buf) );12.6.28

image().fill()

NAME
image().fill() — Modification of pixel values in a rectangular area to a value
SYNOPSIS
fits_image &image( ... ).fill( double value,long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL );DESCRIPTION
image().fill() modifies pixel values in a rectangular area whose location is specified bysecond or later arguments into value.
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are modified, respectively.
Do not use a constant FITS:ALL explicitly.
PARAMETER

150

SFITSIO User’s Reference Guide[I] value
a pixel value to be set[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
an offset pixels from layer index([I] : input, [O] : output)

RETURN VALUE
image().fill() returns a reference to the modified fits image object.
EXAMPLES
The following code sets 1 to all pixel values.
fits.image("Primary").fill(1);12.6.29

image().add()

NAME
image().add() — Addition of pixel values in a rectangular area by the value
SYNOPSIS
fits_image &image( ... ).add( double value,long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL );DESCRIPTION
image().add() adds value to pixel values in a rectangular area whose location is specified
by second or later arguments.
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are modified, respectively.
Do not use a constant FITS::ALL explicitly.
PARAMETER[I] value
a value to be added to pixel values[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
an offset pixels from layer index([I] : input, [O] : output)
RETURN VALUE
image().add() returns a reference to the modified fits image object.
EXAMPLES The following code adds 1 to all pixel values.
fits.image("Primary").add(1);Ver. 1.2.1
12.6.30

151
image().subtract()

NAME
image().subtract() — Subtracting a value from a rectangular area
SYNOPSIS
fits_image &image( ... ).subtract( double value,long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL );DESCRIPTION
image().subtract() subtracts value from pixel values in a rectangular area whose locationis specified by second or later arguments.
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are modified, respectively.
Do not use a constant FITS::ALL explicitly.
PARAMETER[I] value
a value which are subtracted from pixel values[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
an offset pixels from layer index([I] : input, [O] : output)
RETURN VALUE
image().subtract() returns a reference to the modified fits image object.
EXAMPLES The following code subtracts 1.0 from all pixel values.
fits.image("Primary").subtract(1.0);

12.6.31

image().multiply()

NAME
image().multiply() — Multiplication of pixel values in the rectangular area by the value
SYNOPSIS
fits_image &image( ... ).multiply( double value,long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL );DESCRIPTION
image().multiply() multiplies pixel values in a rectangular area whose location is specified
by second or later arguments by value.
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are modified, respectively.
Do not use a constant FITS::ALL explicitly.

152

SFITSIO User’s Reference Guide

PARAMETER[I] value
a value to be multiplied by pixel values[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
layer size an offset pixels from layer index([I] : input, [O] : output)
RETURN VALUE
image().multiply() returns a reference to the modified fits image object.
EXAMPLES
The following code multiplies all pixel values by 2.
fits.image("Primary").multiply(2);12.6.32

image().divide()

NAME
image().divide() — Dividing pixel values in the rectangular area by a value
SYNOPSIS
fits_image &image( ... ).divide( double value,long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL );DESCRIPTION
image().divide() divides pixels of a rectangular area whose location is specified by secondor later arguments by value.
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are modified, respectively.
Do not use a constant FITS::ALL explicitly.
PARAMETER[I] value
a value which divides pixel values[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
layer size an offset pixels from layer index([I] : input, [O] : output)
RETURN VALUE
image().divide() returns a reference to the modified fits image object.
EXAMPLES
The following code divides all pixels by 3.0.
fits.image("Primary").divide(3.0);

Ver. 1.2.1
12.6.33

153
image().fill()

NAME
image().fill() — Modification of pixel values in a rectangular area by a user-defined function
SYNOPSIS
fits_image &image( ... ).fill( double value,
void (*func)(double [],double,long, long,long,long,fits_image *,void *),void *user_ptr,
long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL );DESCRIPTION
image().fill() modifies pixel values in a rectangular area whose location is specified by
fourth or later arguments by a user-defined function (*func).
This member function prepares a temporary buffer to input/output data in the user-defined
function, and performs line-by-line scans in specified rectangular area. For each line scan, 1.
pixel values in this object are converted and stored into the temporary buffer, 2. the userdefined function is called, and 3. data in the temporary buffer are converted and outputted
into pixels in this object. In the conversion of step 1 and 3, SCALE, ZERO and BLANK
are applied. The user’s function has to have a loop to scan all pixel data in the temporary
buffer.
Specifications of arguments in the user-defined function (*func) are as below, and the userdefined function has to store the results into pix[]:
double pix[] ... original pixel values in temporary buffer
double value ... a first argument of image().fill()long n_pix ... number of pix
long axis0 ... a coordinate of x-axis
long axis1 ... a coordinate of y-axis
long axis2 ... a coordinate of z-axis
fits_image *thisp ... a pointer to this object
void *ptr ... a pointer to user_ptr
user_ptr is a pointer which a user can use freely, and it is given to a last argument of auser-defined function.
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are modified. Do not use a constant FITS::ALL explicitly.
PARAMETER[I] value
a pixel value to be set via a user-defined function[I] func
a pointer to a user-defined function[I] user_ptr
an arbitrary pointer which is given to a user-defined function[I] col_index
a pixel index of a column(x-axis)[I] col_size
an offset pixels from col index[I] row_index
a pixel index of a row(y-axis)[I] row_size
an offset pixels from row index[I] layer_index a pixel index of a layer(z-axis)[I] layer_size
an offset pixels from layer index([I] : input, [O] : output)
RETURN VALUE
image().fill() returns a reference to the modified fits image object.

154

SFITSIO User’s Reference Guide

EXAMPLES
The following code sets pixel values over a threshold value thresh to constant values.
static void myfunc( double pix[], double value, long n_pix,
long axis0, long axis1, long axis2,
fits_image *thisp, void *ptr ){long i;for ( i=0 ; i < n_pix ; i++ ) {if ( value < pix[i] ) pix[i] = value;}
return;}::fits_image &primary = fits.image("Primary");
primary.fill( thresh, &myfunc, NULL,
0, primary.col_length(), 0, primary.row_length() );12.6.34

image().copy(), image().cut()

NAME
image().copy(), image().cut() — Copy and cut of pixel values in a rectangular area
SYNOPSIS
void image( ... ).copy( fits_image *dest_img ) const;
void image( ... ).copy( fits_image *dest_img,
long col_index, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL ) const;
fits_image &image( ... ).cut( fits_image *dest_img,
long col_index, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL );DESCRIPTIONThis API copies pixel values in rectangular areas, which are in layers specified layer_index
and layer_size and are defined by indices(col_index, row_index), and offsets(col_size,
row_size), to an object pointed by dest_img.
When each argument of a column, a row, and a layer is not specified, all columns, rows, andlayers are copied.
image().cut() fills the source area with 0 after the copy process.
PARAMETER[O] dest_img
an object which specified rectangular areas are stored to[I]
col_index
a pixel index of a column(x-axis)[I]
col_size
an offset pixels from col index[I]
row_index
a pixel index of a row(y-axis)[I]
row_size
an offset pixels from row index[I]
layer_index a pixel index of a layer(z-axis)[I]layer_size
an offset pixels from layer index([I] : input, [O] : output)

Ver. 1.2.1

155

RETURN VALUE
cut() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to allocate internal memory, it throws an exception derived from SFITSIO(sli::err_rec exception).
EXAMPLES
The following code copies 128 × 128 square area to my_image_buffer, and paste it to theoriginal image at (128, 0).
fits_image my_image_buffer;
fits.image("Primary").copy(&my_image_buffer, 0,128, 0,128);
fits.image("Primary").paste(my_image_buffer, 128, 0);
See also a sample code in §5.10.

12.6.35

image().paste()

NAME
image().paste() — Paste of images in a copy buffer
SYNOPSIS
fits_image &image( ... ).paste( const fits_image &src_img,
long col_index = 0, long row_index = 0,long layer_index = 0 );DESCRIPTION
image().paste() pastes an objects pointed by src_img into an area which is specified by
col_index, row_index, and layer_index.
This API converts data types appropriately when the one of this object and the one of
src_img are not matched, and also when BZERO, BSCALE, and BLANK in headers of the objects
are not matched.
PARAMETER[I] src_img
a source object for copy
[I] col_index
a pixel index of a column(x-axis)[I] row_index
a pixel index of a row(y-axis)[I] layer_index a pixel index of a layer(z-axis)([I] : input, [O] : output)
RETURN VALUE
image().paste() returns a reference to the modified fits image object.
EXCEPTION
If the API fails to allocate internal memory, it throws an exception derived from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.6.34 and also a sample code in §5.10.

156

SFITSIO User’s Reference Guide

12.6.36

image().add()

NAME
image().add() — Adding an image in a copy buffer to an original imageSYNOPSIS
fits_image &image( ... ).add( const fits_image &src_img,
long col_index = 0, long row_index = 0,long layer_index = 0 );DESCRIPTION
image().add() adds an image in an object pointed by src_img to an original image withcoordinates(col_index, row_index) in a layer specified by layer_index. When the pixel of
src_img is NAN, pixels are not modified.
This API converts data types appropriately when the one of the objects and the one of
src_img are not matched, and also when BZERO, BSCALE, and BLANK in headers of the objects
are not matched.
PARAMETER[I] src_img
an object to be added[I] col_index
a pixel index of a column(x-axis)[I] row_index
a pixel index of a row(y-axis)[I] layer_index a pixel index of a layer(z-axis)([I] : input, [O] : output)
RETURN VALUE
image().add() returns a reference to the modified fits image object.
EXAMPLES
An image in a copy buffer is overlapped with an original image by rewriting add from paste()of EXAMPLES in §12.6.34 as below:
fits.image("Primary").add(my_image_buffer, 128, 0);12.6.37

image().subtract()

NAME
image().subtract() — Subtracting an image in a copy buffer from an original imageSYNOPSIS
fits_image &image( ... ).subtract( const fits_image &src_img,
long col_index = 0, long row_index = 0,long layer_index = 0 );DESCRIPTION
image().subtract() subtracts an image in an object pointed by src_img from an original
image with coordinates(col_index, row_index) in a layer specified by layer_index. Whena pixel of src_img is NAN, pixels are not modified.
This API converts data types appropriately when the one of this object and the one of
src_img are not matched, and also when BZERO, BSCALE, and BLANK in headers of the objects
are not matched.

Ver. 1.2.1

157

PARAMETER[I] src_img
an object which are subtracted from an original image[I] col_index
a pixel index of a column(x-axis)[I] row_index
a pixel index of a row(y-axis)[I] layer_index a pixel index of a layer(z-axis)([I] : input, [O] : output)
RETURN VALUE
image().subtract() returns a reference to the modified fits image object.
EXAMPLES
See EXAMPLES in §12.6.36.

12.6.38

image().multiply()

NAME
image().multiply() — Multiplying an original image by an image in a copy buffer
SYNOPSIS
fits_image &image( ... ).multiply( const fits_image &src_img,
long col_index = 0, long row_index = 0,long layer_index = 0 );DESCRIPTION
image().multiply() multiplies an original image with coordinates(col_index, row_index)
in a layer specified by layer_index by an image in an object pointed by src_img. Whenthe pixel of src_img is NAN, pixels are not modified.
This API converts data types appropriately when that of the object and that of src_img do
not match, and also when BZERO, BSCALE, and BLANK in headers of the objects do not match.
PARAMETER[I] src_img
an object which are multiplied to an original image[I] col_index
a pixel index of a column(x-axis)[I] row_index
a pixel index of a row(y-axis)[I] layer_index a pixel index of a layer(z-axis)([I] : input, [O] : output)
RETURN VALUE
image().multiply() returns a reference to the modified fits image object.
EXAMPLES
See EXAMPLES in §12.6.36.

12.6.39

image().divide()

NAME
image().divide() — Dividing an original image by an image in a copy buffer
SYNOPSIS
fits_image &image( ... ).divide( const fits_image &src_img,
long col_index = 0, long row_index = 0,long layer_index = 0 );

158

SFITSIO User’s Reference Guide

DESCRIPTION
image().divide() divides an original image with coordinates(col_index, row_index) in alayer specified by layer_index by an image in an object pointed by src_img. When the
pixel of src_img is NAN, pixels are not modified.
This API converts data types appropriately when that of the object and that of src_img do
not match, and also when BZERO, BSCALE, and BLANK in headers of the objects do not match.
PARAMETER[I] src_img
an object which divides an original image[I] col_index
a pixel index of a column(x-axis)[I] row_index
a pixel index of a row(y-axis)[I] layer_index a pixel index of a layer(z-axis)([I] : input, [O] : output)
RETURN VALUE
image().divide() returns a reference to the modified fits image object.
EXAMPLES
See EXAMPLES in §12.6.36.

12.6.40

image().paste()

NAME
image().paste() — Paste of images in a copy buffer via a user-defined function
SYNOPSIS
fits_image &image( ... ).paste( const fits_image &src_img,
void (*func)(double [],double [],long, long,long,long,fits_image *,void *),void *user_ptr,
long dest_col = 0, long dest_row = 0, long dest_layer = 0 );DESCRIPTION
image().paste() pastes an image in an objects pointed by src_img into a rectangular area
which is specified by dest_col, dest_row, and dest_layer. At this time, pixel values canbe modified by a user-defined function (*func).
This member function prepares a temporary buffer to input/output data in the user-defined
function, and performs line-by-line scans in specified rectangular area. For each line scan, 1.
pixel values in this object are converted and stored into the temporary buffer, 2. the userdefined function is called, and 3. data in the temporary buffer are converted and outputted
into pixels in this object. In the conversion of step 1 and 3, SCALE, ZERO and BLANK
are applied. The user’s function has to have a loop to scan all pixel data in the temporary
buffer.
Specifications of arguments in the user-defined function (*func) are as below, and the userdefined function has to store the results into pix_self[]:
double pix_self[] ... original pixel values
double pix_src[] ... pixel values of src img
long n_pix ... number of pix self or pix src
long axis0 ... a coordinate of x-axis
long axis1 ... a coordinate of y-axis
long axis2 ... a coordinate of z-axis

Ver. 1.2.1

159

fits_image *thisp ... a pointer to this object
void *ptr ... a pointer to user_ptr
user_ptr is a pointer which a user can use freely, and it is given to a last argument of auser-defined function.
When an argument of a column, a row, or a layer is not specified, all columns, rows, andlayers are modified. Do not use a constant FITS::ALL explicitly.
PARAMETER[I] src_img
an source object to be set[I] func
a pointer to a user-defined function[I] user_ptr
an arbitrary pointer which is given to a user-defined function[I] dest_cola pixel index of a column(x-axis) in a destination[I] dest_row
a pixel index of a row(y-axis) in a destination[I] dest_layer a pixel index of a layer(z-axis) in a destination([I] : input, [O] : output)
RETURN VALUE
image().paste() returns a reference to the modified fits image object.
EXAMPLES
For more information about a user-defined function, see EXAMPLES in §12.6.33.

12.6.41

image().stat pixels()

NAME
image().stat pixels() — Compute pixel statistics of a rectangular area
SYNOPSIS
long image( ... ).stat_pixels( double results[], size_t results_len,
const char *options,long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL ) const;
long image( ... ).stat_pixels( fits_header *results, const char *options,long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL ) const;
DESCRIPTION
These member functions compute some statistics of pixels in a rectangular area specified by
col_index or later arguments. The results are stored into an array or a fits header object
pointed by results.
To select required statistics, programmers set a string such as "results=mean,stddev,median"
to argument options. Following strings can be set after results=:
npix ... the number of pixels used to do the statistics
mean ... the mean of the pixel distribution
stddev ... the standard deviation of the pixel distribution
median ... the median of the pixel distribution38)
38)

This is not an approximate value such as ‘midpt’ of IRAF but true median. SFITSIO calculates it withhigh-speed.

160

SFITSIO User’s Reference Guide
min ... the minimum pixel value
max ... the maximum pixel value
skew ... the skew of the pixel distribution
kurtosis ... the kurtosis of the pixel distribution
There are two types of results arguments; one is a simple array in which statistics are stored
in order of elements in results= string, another is a fits header object in which keywords(e.g., "MEAN") and statistics are stored.

PARAMETER[O] results

an address of an array or a fits header object in which the statistics
are stored[I]
results_len length of array results[I]
options
an option string for computing statistics[I]
col_index
a pixel index of a column(x-axis)[I]
col_size
an offset pixels from col index[I]
row_index
a pixel index of a row(y-axis)[I]
row_size
an offset pixels from row index[I]
layer_index a pixel index of a layer(z-axis)[I]layer_size
an offset pixels from layer index([I] : input, [O] : output)

RETURN VALUE
nonnegative :negative:

total number of valid pixels
error (e.g. invalid arguments are specified)

EXAMPLES
Next code computes statistics of an image in Primary HDU, and display them. Programmers
can use an object of fits header class to obtain the results of statistics.
fits_header stat_results;
const char *stat_options = "results=npix,mean,stddev,min,max,median";long i;/* Compute statistics */if ( fits.image("Primary").stat_pixels(&stat_results, stat_options) < 0 ) {/* error handling */}/* Display results */for ( i=0 ; i < stat_results.length() ; i++ ) {printf("%s = %.15g\n", stat_results.at(i).keyword(),stat_results.at(i).dvalue());}
To get a value from stat_results object, programmers can handle it like associative arraysuch as stat_results.at("NPIX").dvalue().
image().stat_pixels() is used in the example code in exercise 3 in §1.1.
See also tools/stat pixels.cc in SFITSIO source package.
12.6.42

image().combine layers()

NAME
image().combine layers() — Combine 2-d images in specified cubic area

Ver. 1.2.1

161

SYNOPSIS
long image( ... ).combine_layers( fits_image *dest_img, const char *options,long col_index = 0, long col_size = FITS::ALL,
long row_index = 0, long row_size = FITS::ALL,
long layer_index = 0, long layer_size = FITS::ALL ) const;
DESCRIPTION
image().combine_layers() combines 2-d images in the cubic area of image buffer specified
by col_index or later arguments. The results are stored into a fits image object pointed by
dest_img.
Programmers can select method of combine and type of the output image. For example,
to perform combine with average and to output the result with 4-byte floating point, set"combine=average outtype=float" to options.
Programmers can set a string after ‘combine=’ to select method of combine: average, median,sum, min, or max.
Programmers can set a string after ‘outtype=’ to select type of output image:
short ... 2-byte signed integer
ushort ... 2-byte unsigned integer (BZERO=32768.0)
long ... 4-byte signed integer
longlong ... 8-byte signed integer
float ... 4-byte floating point
double ... 8-byte floating point
PARAMETER[O] dest_img
an address of a fits image object in which the combined image is stored[I]
options
an option string for combine[I]
col_index
a pixel index of a column(x-axis)[I]
col_size
an offset pixels from col index[I]
row_index
a pixel index of a row(y-axis)[I]
row_size
an offset pixels from row index[I]
layer_index a pixel index of a layer(z-axis)[I]layer_size
an offset pixels from layer index([I] : 入力，[O] : 出力)
RETURN VALUE
nonnegative :negative:

total number of valid pixels
error (e.g. invalid arguments are specified)

EXAMPLES
Next code is an example to combine three 2-d images using median. Contents of first FITS
file is loaded into ‘fits0’, second and third images are inserted into second and third layers of
the image buffer in ‘fits0’, and combine of three 2-d images are performed. In this example,
codes for error handling are omitted for readability.
fitscc fits0, fits1;/* read and prepare */fits0.read_stream("raw_image_0.fits");/* 2d image No.1 */fits0.image("Primary").resize(2, 3);/* resize z-axis => 3 */fits1.read_stream("raw_image_1.fits");/* 2d image No.2 */fits0.image("Primary").paste(fits1.image("Primary"), 0L, 0L, 1L);
fits1.read_stream("raw_image_2.fits");/* 2d image No.3 */162

SFITSIO User’s Reference Guide
fits0.image("Primary").paste(fits1.image("Primary"), 0L, 0L, 2L);/* combine (fits1.image("Primary") will be overwritten) */fits0.image("Primary").combine_layers(&fits1.image("Primary"),"combine=median outtype=float");/* output combined image */fits1.write_stream("combined_image.fits");
See also tools/combine images.cc in SFITSIO source package.

12.7

APIs for low-level manipulation of an Image HDU

In this section, we describe APIs to manipulate an Image HDU at low-level. At low-level APIs,
users have to do a data conversion, using BZERO and BSCALE. Usually, the APIs shown here are
not necessary for the manipulation of an Image HDUs, however they may help to speed up the
execution.
Every argument of “image( ... )” of all APIs in this section is an HDU index(long index)
or an HDU name(const char *hduname), therefore we skip the description of this argument.
12.7.1

image().data array()

NAME
image().data array() — A reference to an object for managing a data buffer
SYNOPSIS
sli::mdarray &image( ... ).data_array();
const sli::mdarray &image( ... ).data_array() const;
const sli::mdarray &image( ... ).data_array_cs() const;
DESCRIPTION
An image buffer of the fits image class is managed by the mdarray class of SLLIB. data array()is used when users conduct an opeartion with the mdarray class.
For more information on the mdarray class, see a SLLIB manual.

12.7.2

image().data ptr()

NAME
image().data ptr() — An address of a data buffer in an object
SYNOPSIS
void *image( ... ).data_ptr( long axis0 = 0,long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );void *image( ... ).data_ptr_v( long num_axisx,
long axis0, long axis1, long axis2, ... );void *image( ... ).va_data_ptr_v( long num_axisx,
long axis0, long axis1, long axis2, va_list ap );DESCRIPTION
image().data ptr() returns an address of an internal image data buffer at the axis0-th
column, the axis1-th row, and the axis2-th layer. When the coordinate argument is out ofrange, NULL is returned.

Ver. 1.2.1

163

axis0, axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional,
2-dimensional, and 3(or more)-dimensional data by the number of arguments.
The returned value is an address of an internal buffer in an object, and it is invalid when theobject is revoked or the type or the size of the buffer is changed.
The returned address is cast into any one of fits::double_t *, fits::float_t *,fits::longlong_t *, fits::long_t *, fits::short_t *, fits::byte_t * depending on
a current FITS data type.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
integer value :NULL:

an address of internal image data buffer
error(e.g. A coordinate argument is out of range.)

EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO (sli::err_rec exception).
EXAMPLES
fits::double_t *img_ptr = (fits::double_t *)fits.image("Primary").data_ptr();See also a sample code in §5.11.

12.7.3

image().get data()

NAME
image().get data() — Get a raw image data
SYNOPSIS
ssize_t image( ... ).get_data( void *dest_buf, size_t buf_size,
long axis0 = 0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
ssize_t image( ... ).get_data_v( void *dest_buf, size_t buf_size,
long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
ssize_t image( ... ).va_get_data_v( void *dest_buf, size_t buf_size,
long num_axisx,
long axis0, long axis1, long axis2,
va_list ap ) const;
DESCRIPTION
image().get data() copies raw image data at the axis0-th column, the axis1-th row, andthe axis2-th layer to dest_buf up to buf_size bytes.

164

SFITSIO User’s Reference Guide
axis0, axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional,
2-dimensional, and 3(or more)-dimensional data by the number of arguments.
The address specified by dest_buf is cast into any one of fits::double_t *, fits::float_t *,fits::longlong_t *, fits::long_t *, fits::short_t *, fits::byte_t * depending on
a current FITS data type.
Do not use a constant FITS::INDEF explicitly.

PARAMETER[O] dest_buf
an address of an obtained image data[I]buf_sizea size of dest buf in byes
[I]
axis0
a pixel location in a column(x-axis)
[I]
axis1
a pixel location in a row(y-axis)
[I]
axis2
a pixel location in a layer(z-axis)[I]
num_axisx the number of axes specified as arguments[I]...
all location data of pixels in each axis[I]ap
all location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
nonnegative integer
negative::the number of copied bytes with a sufficient buffer size
error(e.g. Invalid arguments are specified and the copy process iscancelled.)

EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO (sli::err_rec exception).
EXAMPLES
size_t buf_size = fits.image("Primary").bytes() * fits.image("Primary").length();fits::double_t *dest_buf = (fits::double_t *)malloc(buf_size);if ( dest_buf == NULL ) {/* error handling */}fits.image("Primary").get_data(dest_buf, buf_size);

12.7.4

image().put data()

NAME
image().put data() — Put a raw image data
SYNOPSIS
ssize_t image( ... ).put_data( const void *src_buf, size_t buf_size, long axis0 = 0,long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );ssize_t image( ... ).put_data_v( const void *src_buf, size_t buf_size,
long num_axisx,
long axis0, long axis1, long axis2, ... );ssize_t image( ... ).va_put_data_v( const void *src_buf, size_t buf_size,
long num_axisx,
long axis0, long axis1, long axis2,
va_list ap );Ver. 1.2.1

165

DESCRIPTION
image().put data() copies raw image data pointed by src_buf to the axis0-th column,
the axis1-th row, and the axis2-th layer of an object up to buf_size bytes.
axis0, axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional,
2-dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] src_buf
an address of a source image data
[I] buf_size
a size of src buf in bytes[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
nonnegative integer
negative::the number of copied bytes with a sufficient buffer size
error(e.g. Invalid arguments are specified and the copy process iscancelled.)

EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO (sli::err_rec exception).
EXAMPLES
size_t buf_size = fits.image("Primary").bytes() * fits.image("Primary").length();fits::double_t *src_buf = (fits::double_t *)malloc(buf_size);::fits.image("Primary").put_data(src_buf, buf_size);

12.7.5

image().double value()

NAME
image().double value() — Return raw image data
SYNOPSIS
double image( ... ).double_value( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
double image( ... ).double_value_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
double image( ... ).va_double_value_v( long num_axisx,
long axis0, long axis1, long axis2, va_list ap ) const;
DESCRIPTION
image().double value() returns a raw pixel value at the axis0-th column, the axis1-th
row, and the axis2-th layer. image().dvalue()(see §12.6.10.) returns a pixel value which
is subject to BZERO and BSCALE.

166

SFITSIO User’s Reference Guideaxis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.

PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().double value() returns a pixel value.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO (sli::err_rec exception).
EXAMPLES
The following code displays all pixel values in 0-th row.
long idx;for ( idx=0 ; idx < fits.image("Primary").col_length() ; idx++ ) {printf("index[%ld]=[%lf]\n", idx, fits.image("Primary").double_value(idx,0));}12.7.6

image().float value()

NAME
image().float value() — Return raw image data
SYNOPSIS
float image( ... ).float_value( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
float image( ... ).float_value_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
float image( ... ).va_float_value_v( long num_axisx,
long axis0, long axis1, long axis2, va_list ap ) const;
DESCRIPTION
image().float value() returns a raw pixel value at the axis0-th column, the axis1-th
row, and the axis2-th layer. Use image().dvalue()(see §12.6.10.) when you need the pixel
value which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.

Ver. 1.2.1

167

PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().float value() returns a pixel value.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO (sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.5.

12.7.7

image().longlong value()

NAME
image().longlong value() — Return raw image data
SYNOPSIS
long long image( ... ).longlong_value( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
long long image( ... ).longlong_value_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
long long image( ... ).va_longlong_value_v( long num_axisx,
long axis0, long axis1, long axis2, va_list ap ) const;
DESCRIPTION
image().longlong value() returns a raw pixel value at the axis0-th column, the axis1-th
row, and the axis2-th layer. Use image().dvalue(), image().lvalue() or image().llvalue()(see§12.6.10) when you need the pixel value which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().longlong value() returns a pixel value.

168

SFITSIO User’s Reference Guide

EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.5.

12.7.8

image().long value()

NAME
image().long value() — Return raw image data
SYNOPSIS
long image( ... ).long_value( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
long image( ... ).long_value_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
long image( ... ).va_long_value_v( long num_axisx,
long axis0, long axis1, long axis2, va_list ap ) const;
DESCRIPTION
image().long value() returns a raw pixel value at the axis0-th column, the axis1-th row,and the axis2-th layer. Use image().dvalue(), image().lvalue() or image().llvalue()(see§12.6.10) when you need the pixel value which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().long value() returns a pixel value.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.5.

12.7.9image().short value()

NAME
image().short value() — Return raw image data

Ver. 1.2.1

169

SYNOPSIS
short image( ... ).short_value( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
short image( ... ).short_value_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
short image( ... ).va_short_value_v( long num_axisx,
long axis0, long axis1, long axis2, va_list ap ) const;
DESCRIPTION
image().short value() returns a raw pixel value at the axis0-th column, the axis1-th row,and the axis2-th layer. Use image().dvalue(), image().lvalue() or image().llvalue()(see§12.6.10) when you need the pixel value which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().short value() returns a pixel value.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.5.
12.7.10

image().byte value()

NAME
image().byte value() — Return raw image data
SYNOPSIS
unsigned char image( ... ).byte_value( long axis0, long axis1 = FITS::INDEF,
long axis2 = FITS::INDEF ) const;
unsigned char image( ... ).byte_value_v( long num_axisx,
long axis0, long axis1, long axis2, ... ) const;
unsigned char image( ... ).va_byte_value_v( long num_axisx,
long axis0, long axis1, long axis2, va_list ap ) const;
DESCRIPTION
image().byte value() returns a raw pixel value at the axis0-th column, the axis1-th row,and the axis2-th layer. Use image().dvalue(), image().lvalue() or image().llvalue()(see§12.6.10) when you need the pixel value which is reflected by BZERO and BSCALE.

170

SFITSIO User’s Reference Guideaxis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.

PARAMETER[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().byte value() returns a pixel value.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.5.
12.7.11

image().assign double()

NAME
image().assign double() — Assign raw image value
SYNOPSIS
fits_image &image( ... ).assign_double( double value, long axis0,
long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );fits_image &image( ... ).assign_double_v( double value, long num_axisx,
long axis0, long axis1, long axis2, ... );fits_image &image( ... ).va_assign_double_v( double value, long num_axisx,
long axis0, long axis1, long axis2, va_list ap );DESCRIPTION
image().assign double() modifies a raw pixel value at the axis0-th column, the axis1-th
row, and the axis2-th layer. Use image().assign()(see §12.6.12.) modifies data by a pixel
value which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] value
a value to be set[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)

Ver. 1.2.1

171

RETURN VALUE
image().assign double() returns a reference to the modified fits image object.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
The following code assigns 0 to all pixel values in 0-th row.
long idx;for ( idx=0 ; idx < fits.image("Primary").col_length() ; idx++ ) {fits.image("Primary").assign_double(0.0, idx,0);}12.7.12

image().assign float()

NAME
image().assign float() — Assign raw image value
SYNOPSIS
fits_image &image( ... ).assign_float( float value, long axis0,
long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );fits_image &image( ... ).assign_float_v( float value, long num_axisx,
long axis0, long axis1, long axis2, ... );fits_image &image( ... ).va_assign_float_v( float value, long num_axisx,
long axis0, long axis1, long axis2, va_list ap );DESCRIPTION
image().assign float() modifies a raw pixel value at the axis0-th column, the axis1-th
row, and the axis2-th layer. image().assign()(see §12.6.12) modifies data by a pixel value
which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] value
a value to be set[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().assign float() returns a reference to the modified fits image object.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).

172

SFITSIO User’s Reference Guide

EXAMPLES
See EXAMPLES in §12.7.11.
12.7.13

image().assign longlong()

NAME
image().assign longlong() — Assign raw image value
SYNOPSIS
fits_image &image( ... ).assign_longlong( long long value, long axis0,
long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );fits_image &image( ... ).assign_longlong_v( long long value, long num_axisx,
long axis0, long axis1, long axis2, ... );fits_image &image( ... ).va_assign_longlong_v( long long value, long num_axisx,
long axis0, long axis1, long axis2, va_list ap );DESCRIPTION
image().assign longlong() modifies a raw pixel value at the axis0-th column, the axis1th row, and the axis2-th layer. image().assign()(see §12.6.12) modifies data by a pixel
value which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] value
a value to be set[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().assign longlong() returns a reference to the modified fits image object.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.11.
12.7.14

image().assign long()

NAME
image().assign long() — Assign raw image value
SYNOPSIS
fits_image &image( ... ).assign_long( long value, long axis0,
long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );Ver. 1.2.1

173

fits_image &image( ... ).assign_long_v( long value, long num_axisx,
long axis0, long axis1, long axis2, ... );fits_image &image( ... ).va_assign_long_v( long value, long num_axisx,
long axis0, long axis1, long axis2, va_list ap );DESCRIPTION
image().assign long() modifies a raw pixel value at the axis0-th column, the axis1-th
row, and the axis2-th layer. image().assign()(see §12.6.12) modifies data by a pixel value
which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] value
a value to be set[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().assign long() returns a reference to the modified fits image object.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.11.
12.7.15

image().assign short()

NAME
image().assign short() — Assign raw image value
SYNOPSIS
fits_image &image( ... ).assign_short( short value, long axis0,
long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );fits_image &image( ... ).assign_short_v( short value, long num_axisx,
long axis0, long axis1, long axis2, ... );fits_image &image( ... ).va_assign_short_v( short value, long num_axisx,
long axis0, long axis1, long axis2, va_list ap );DESCRIPTION
image().assign short() modifies a raw pixel value at the axis0-th column, the axis1-th
row, and the axis2-th layer. image().assign()(see §12.6.12) modifies data by a pixel value
which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.

174

SFITSIO User’s Reference Guide
Do not use a constant FITS::INDEF explicitly.

PARAMETER[I] value
a value to be set[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)
RETURN VALUE
image().assign short() returns a reference to the modified fits image object.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.11.

12.7.16

image().assign byte()

NAME
image().assign byte() — Assign raw image value
SYNOPSIS
fits_image &image( ... ).assign_byte( unsigned char value, long axis0,
long axis1 = FITS::INDEF, long axis2 = FITS::INDEF );fits_image &image( ... ).assign_byte_v( unsigned char value, long num_axisx,
long axis0, long axis1, long axis2, ... );fits_image &image( ... ).va_assign_byte_v( unsigned char value, long num_axisx,
long axis0, long axis1, long axis2, va_list ap );DESCRIPTION
image().assign byte() modifies a raw pixel value at the axis0-th column, the axis1-th
row, and the axis2-th layer. image().assign()(see §12.6.12) modifies data by a pixel value
which is reflected by BZERO and BSCALE.
axis1, axis2 are optional, and n-dimensional data can be treated as 1-dimensional, 2dimensional, and 3(or more)-dimensional data by the number of arguments.
Do not use a constant FITS::INDEF explicitly.
PARAMETER[I] value
a value to be set[I] axis0
a pixel location in a column(x-axis)[I] axis1
a pixel location in a row(y-axis)[I] axis2
a pixel location in a layer(z-axis)[I] num_axisx the number of axes specified as arguments[I] ...
all location data of pixels in each axis
[I] apall location data of pixels in each axis([I] : input, [O] : output)

Ver. 1.2.1

175

RETURN VALUE
image().assign byte() returns a reference to the modified fits image object.
EXCEPTION
When invalid values are specified as variable arguments, the API throws an exception derived
from SFITSIO(sli::err_rec exception).
EXAMPLES
See EXAMPLES in §12.7.11.

176

SFITSIO User’s Reference Guide

12.8

Manipulation of Ascii Table HDU and Binary Table HDU

In this section, we describe APIs for manipulating ASCII Table HDU and Binary Table HDU. In
SFITSIO, the ASCII Table is treated as an only case of the string column (i.e., TTYPEn of header
is xA) of Binary Table. Therefore, both the ASCII Table and the Binary Table can be treated via
the same APIs.
APIs are classified into two groups. The first case is,¨§¥value = fits.table( ... ).function( ... );The second case is,¨§value = fits.table( ... ).col( ... ).function( ... );value = fits.table( ... ).colf( ... ).function( ... );¦¥¦The argument for table( ... ) is HDU number (long index) or HDU name (const char *hduname).
The argument for col() is column index(long index) or column name (const char *col_name).
The argument for colf() is column name written as the format of libc’s printf().
For the rest of this document, the argument of table( ... ), col( ... ) and colf( ... )is the same as above, so the explanation is omitted.
12.8.1

table().hduname(), table().assign hduname()

NAME
table().assign hduname(), table().hduname() — Manipulate HDU NameSYNOPSIS
const char *table( ... ).hduname();const char *table( ... ).extname();fits_table &table( ... ).assign_hduname( const char *name );fits_table &table( ... ).assign_extname( const char *name );DESCRIPTION
table().hduname() returns HDU name. table().assign_hduname() sets HDU name. The
argument name is reflected to EXTNAME.
PARAMETER[I] name HDU name([I] : input, [O] : output)
RETURN VALUE
table().hduname() returns an address of HDU name string.
table().assign_hduname() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, to resize the space when changing HDU name), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
printf("HDU Name=\%s\n", fits.table("EVENT").hduname());

Ver. 1.2.1
12.8.2177

table().hduver(), table().assign hduver()

NAME
table().assign hduver(), table().hduver() — Manipulate HDU version number
SYNOPSIS
long long table( ... ).hduver();long long table( ... ).extver();fits_table &table( ... ).assign_hduver( long long ver );fits_table &table( ... ).assign_extver( long long ver );DESCRIPTION
table().hduver() returns HDU version number.
table().assign_hduver() sets HDU version number. The argument ver is reflected to
EXTVER.
PARAMETER[I] ver version number([I] : input, [O] : output)
RETURN VALUE
table().hduver() returns the HDU version number.
table().assign_hduver() returns a reference to the fits table object.
EXAMPLES
printf("HDU Version=%lld\n", fits.table("EVENT").hduver());
12.8.3

table().col length()

NAME
table().col length() — Number of columns
SYNOPSIS
long table( ... ).col_length() const;
RETURN VALUE
table().col length() returns the number of columns.
EXAMPLES
printf("Column Length=%ld\n", fits.table("EVENT").col_length());
12.8.4

table().row length()

NAME
table().row length() — Number of rows
SYNOPSIS
long table( ... ).row_length() const;
RETURN VALUE
table().row length() returns the number of rows.
EXAMPLES
printf("Row Length=%ld\n", fits.table("EVENT").row_length());

178
12.8.5SFITSIO User’s Reference Guide
table().heap length()

NAME
table().heap length() — Byte length of heap area
SYNOPSIS
long table( ... ).heap_length() const;
RETURN VALUE
table().heap length() returns byte length of heap area owned by the table.
12.8.6table().col index()

NAME
table().col index() — Column index
SYNOPSIS
long table( ... ).col_index( const char *col_name ) const;
DESCRIPTION
table().col_index() returns an index of the column of which the name is col name.
PARAMETER[I] col_name column name([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value (error)::

column index.
not found.

EXAMPLES
The following code displays all the column name and index of the table.
long idx;for ( idx=0 ; idx < fits.table("EVENT").col_length() ; idx++ ) {const char *col_name = fits.table("EVENT").col_name(idx);
long col_idx = fits.table("EVENT").col_index(col_name);printf("Column Name=%s\tColumn Number=%ld\n", col_name, col_idx);}
12.8.7table().col name()

NAME
table().col name() — Column name
SYNOPSIS
const char *table( ... ).col_name( long col_index ) const;
DESCRIPTION
table().col name() returns the name of the column of which the index is col index.
PARAMETER[I] col_index column index([I] : input, [O] : output)

Ver. 1.2.1

179

RETURN VALUE
table().col name() returns an address of the column name string.
EXAMPLES
See EXAMPLES of 12.8.6
12.8.8table().col().type()

NAME
table().col().type() — Column typeSYNOPSIS
int table( ... ).col( ... ).type() const;
DESCRIPTION
table().col().type() returns the type of column.
The type is one of the following – FITS::DOUBLE_T, FITS::FLOAT_T, FITS::LONGLONG_T,
FITS::LONG_T, FITS::SHORT_T, FITS::BYTE_T, FITS::BIT_T, FITS::LOGICAL_T, FITS::COMPLEX_T,
FITS::DOUBLECOMPLEX_T, FITS::ASCII_T, FITS::LONGARRDESC_T, LLONGARRDESC_T.
EXAMPLES
The example code gets following information of all the columns in the table.
• Type of the column• Bytes of the column type
• Number of elements within the column• Byte length of the column
long idx;for ( idx=0 ; idx < fits.table("EVENT").col_length() ; idx++ ) {int c_type = fits.table("EVENT").col(idx).type();long c_bytes = fits.table("EVENT").col(idx).bytes();long c_elem_len = fits.table("EVENT").col(idx).elem_length();long c_elem_byte_len = fits.table("EVENT").col(idx).elem_byte_length();::}12.8.9table().col().heap is used()

NAME
table().col().heap is used() — Test the column for using variable length array
SYNOPSIS
bool table( ... ).col( ... ).heap_is_used() const;
DESCRIPTION
table().col().heap_is_used() member function returns true when the column has variable length array, otherwise it returns false.

180

SFITSIO User’s Reference Guide

12.8.10table().col().heap type()

NAME
table().col().heap type() — Type of heap used by a column
SYNOPSIS
int table( ... ).col( ... ).heap_type() const;
DESCRIPTION
table().col().heap_type() returns the type of heap used by specified column.
The type is one of the following – FITS::DOUBLE_T, FITS::FLOAT_T, FITS::LONGLONG_T,
FITS::LONG_T, FITS::SHORT_T, FITS::BYTE_T, FITS::BIT_T, FITS::LOGICAL_T, FITS::COMPLEX_T,
FITS::DOUBLECOMPLEX_T, FITS::ASCII_T.

12.8.11table().col().bytes()

NAME
table().col().bytes() — Bytes of column typeSYNOPSIS
long table( ... ).col( ... ).bytes() const;
DESCRIPTION
When the type of column is not FITS::ASCII_T, table().col().bytes() function returns
the bytes of column type. For example, if column type is FITS::DOUBLE_T, then it returns
sizeof(fits::double t). When the type of column is FITS::BIT_T, it returns 1.
When the column type is FITS::ASCII_T, it returns the string length of minimum element in
the column determined by specification of TFORMn and TDIMn. Concrete examples are shownin the following table.
TFORMn and TDIMn
TFORMn = ’120A’
TFORMn = ’120A10’
TFORMn = ’120A10’
TDIMn = ’(6,2)’
TFORMn = ’120A’
TDIMn = ’(10,6,2)’.bytes()120
10.dcol length().drow length().elem length()

1
12

1
1

1
12

10

6

2

12

10

6

2

12

RETURN VALUE
table().col().bytes() returns the bytes of column type.
EXAMPLES
See EXAMPLES of 12.8.8

12.8.12table().col().elem byte length()

NAME
table().col().elem byte length() — Byte length of the column
SYNOPSIS
long table( ... ).col( ... ).elem_byte_length() const;

Ver. 1.2.1

181

DESCRIPTION
table().col().elem byte length() returns byte length of the column. For example, if
TTYPEn is 16D, it returns sizeof(fits::double t)*16.
RETURN VALUE
table().col().elem byte length() returns the byte length of the column.
EXAMPLES
See EXAMPLES of 12.8.8

12.8.13table().col().elem length()

NAME
table().col().elem length() — Number of elements in the column
SYNOPSIS
long table( ... ).col( ... ).elem_length() const;
DESCRIPTION
table().col().elem length() returns the number of elements in the column.
If column type is not FITS::ASCII_T – for example, when TTYPEn is 16D, it returns 16 (norelation with TDIMn).
If column type is FITS::ASCII_T, See the table in table().col().bytes() (12.8.11)
RETURN VALUE
table().col().elem length() returns the number of elements in the column.
EXAMPLES
See EXAMPLES of 12.8.8

12.8.14table().col().dcol length()

NAME
table().col().dcol length() — Number of elements in a row defined by TDIMnSYNOPSIS
long table( ... ).col( ... ).dcol_length() const;
DESCRIPTION
table().col().dcol length() returns a number of elements in a row in a column definedby TDIMn of column.
If the column type is not FITS::ASCII_T – for example, TDIMn is (8x2), it returns 8.
If the column type is FITS::ASCII_T, See the table in table().col().bytes() (12.8.11)
RETURN VALUE
table().col().dcol length() returns the number of elements in the row defined by TDIMn.
EXAMPLES
long dcol_count = fits.table("EVENT").col(0L).dcol_length();182

SFITSIO User’s Reference Guide

12.8.15

table().col().drow length()

NAME
table().col().drow length() — Number of rows defined by TDIMnSYNOPSIS
long table( ... ).col( ... ).drow_length() const;
DESCRIPTION
table().col().drow length() returns number of rows defined by TDIMn.
In the case of the colunm type except FITS::ASCII_T, it returns 2 for a column with (8x2)of its TDIMn.
See table (12.8.11) in table().col().bytes(),if column type is FITS::ASCII_T.
RETURN VALUE
table().col().drow length() returns the number of rows defined by TDIMn.
EXAMPLES
long drow_count = fits.table("EVENT").col(0L).drow_length();12.8.16table().col().heap bytes()

NAME
table().col().heap bytes() — Bytes of heap typeSYNOPSIS
long table( ... ).col( ... ).heap_bytes() const;
DESCRIPTION
table().col().heap bytes() function returns the bytes of heap type of specified column.
For example, if heap type is FITS::DOUBLE_T, then it returns sizeof(fits::double t).
When the type of heap is FITS::BIT_T, it returns 1.

12.8.17table().col().max array length()

NAME
table().col().max array length() — Maximum length of variable length array
SYNOPSIS
long table( ... ).col( ... ).max_array_length() const;
DESCRIPTIONThis member function returns maximum length of variable length array of specified column.

12.8.18

table().col().array length()

NAME
table().col().array length() — Length of variable length array
SYNOPSIS
long table( ... ).col( ... ).array_length( long row_idx, long elem_idx = 0 ) const;

Ver. 1.2.1

183

DESCRIPTIONThis member function returns length of variable length array of specified column and row.
A negative value is returned for errors.

12.8.19

table().col().definition()

NAME
table().col().definition() — Definition of column
SYNOPSIS
const fits::table_def &table( ... ).col( ... ).definition() const;
DESCRIPTION
table().col().definition() returns the reference to a structure object defining the column. It is used when copying the definition of the column to that of another column.
RETURN VALUE
table().col().definition() returns a reference to table def object.
EXAMPLES
See examples in 12.8.46

12.8.20

table().col().dvalue()

NAME
table().col().dvalue() — Returns cell value as a real number value
SYNOPSIS
double table( ... ).col( ... ).dvalue( long row_index ) const;
double table( ... ).col( ... ).dvalue( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
double table( ... ).col( ... ).dvalue( long row_index,
long elem_index, long repetition_idx = 0 ) const;
DESCRIPTION
table().col().dvalue() reflects TZEROn and TSCALn to the value of cell and returns it as areal number value. If the value is NULL, it returns NAN. It returns NAN also when the value ofthe cell equals to that of TNULLn in ASCII tables or in integer type columns of binary tables.
TZEROn and TSCALn value of header is valid when TFORMn of binary table includes ’B’,’I’,’J’,’K’,’E’,or ’D’, or when , TFORMn of ASCII table includes ’I’,’L’,’F’,’E’, ’G’, or’D’.39)When the column type is boolean, it returns 1 if the value is ’T’, and returns 0 if the value
is ’F’, otherwise it returns NAN.
When column of binary table is string type or when the TFORMn of column in ASCII table
does not represent numeric value, it directly returns the real number value converted fromthe string of cell.
39)

SFITSIO supports ’L’ and ’G’ which are not included in the definition of FITS.

184

SFITSIO User’s Reference Guide
If the TFORMn of column in ASCII table does represent numeric value, it converts the stringof cell to real number value and covert it by TZEROn and TSCALn and returns it.
Since it converts string of cell by removing spaces and atof() of libc, the convertible string isdecimal integer, hex integer, or real number value.
If the argument is NULL or invalid, it returns NAN.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.

PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().dvalue() returns the cell value.
EXAMPLES
Following code displays all cell values of the column “TIME” in the table “EVENT”.
fits_table_col &col_ref = fits.table("EVENT").col("TIME");
long i;for ( i=0 ; i < col_ref.length() ; i++ ) {printf("%f\n",col_ref.dvalue(i));}
12.8.21

table().col().lvalue(), table().col().llvalue()

NAME
table().col().lvalue(), table().col().llvalue() — Return cell value as integer
SYNOPSIS
long table( ... ).col( ... ).lvalue( long row_index ) const;
long table( ... ).col( ... ).lvalue( long row_index,
const char *elem_name, long repetiti_idx = 0 ) const;
long table( ... ).col( ... ).lvalue( long row_index,
long elem_index, long repetition_idx = 0 ) const;
long long table( ... ).col( ... ).llvalue( long row_index ) const;
long long table( ... ).col( ... ).llvalue( long row_index,
const char *elem_name, long repetiti_idx = 0 ) const;
long long table( ... ).col( ... ).llvalue( long row_index,
long elem_index, long repetition_idx = 0 ) const;

Ver. 1.2.1

185

DESCRIPTION
table().col().lvalue() and table().col().llvalue() reflect TZEROn and TSCALn to thevalue of cell and return the nearest integer of the real number value. If the value is NULL,
it returns INDEF LONG or INDEF LLONG. It returns INDEF LONG or INDEF LLONG also when thevalue of cell equals to that of TNULLn of ASCII table or that of integer type column of binary
table.
TZEROn and TSCALn value of header is valid when TFORMn of binary table includes ’B’,’I’,’J’,’K’,’E’,or ’D’, or , TFORMn of ASCII table includes ’I’,’L’,’F’,’E’, ’G’, or ’D’.40)
When the column type is boolean, it returns 1 if the value is ’T’, and returns 0 if the value
is ’F’, otherwise it returns INDEF LONG or INDEF LLONG.
When column of binary table is string type or when the TFORMn of column in ASCII table
does not represent numeric value, it directly returns the nearest integer of real number value
converted from the string of cell.
If the TFORMn of column in ASCII table does represent numeric value, it converts the stringof cell to real number value and covert it by TZEROn and TSCALn and returns the nearest
integer.
Since it converts string of cell by removing spaces and atof() of libc, the convertible string isdecimal integer, hex integer, or real number value.
If the argument is NULL or invalid, it returns INDEF LONG or INDEF LLONG which is cast to
the returned type.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().lvalue() and table().col().llvalue() return the cell value.
EXAMPLES
See EXAMPLES of 12.8.20
12.8.22

table().col().bvalue()

NAME
table().col().bvalue() — Returns cell as boolean
SYNOPSIS
bool table( ... ).col( ... ).bvalue( long row_index ) const;bool table( ... ).col( ... )40)

SFITSIO supports ’L’ and ’G’ which are not included in the definition of FITS.

186

SFITSIO User’s Reference Guide.bvalue( long row_index,
const char *elem_name, long repetiti_idx = 0 ) const;bool table( ... ).col( ... ).bvalue( long row_index,
long elem_index, long repetition_idx = 0 ) const;

DESCRIPTION
table().col().bvalue() returns cell value as boolean. The return value is true or false. If
you need three kinds of value, ’T’,’F’ and ’U’, then use table().col().logical value() (12.9.19).
When the column type is boolean type,it returns true if the value is ’T’ and it returns false
if the value is ’F’.
In the case of string type column of binary table that the TFORMn of column in ASCII table
does not represent numeric value, it converts cell string to real number, and if the nearest
integer is 0 then it returns false, otherwise it returns true.
If the TFORMn of column in ASCII table does represent numeric value, it converts the string ofcell to real number value and covert it further by TZEROn and TSCALn. If the nearest integer
to the converted value is 0, then it returns false, otherwise true. Since it converts stringof cell by atof() of libc after removing spaces, the convertible string is decimal integer, hex
integer, or real number value.
When the cell string cannot be convert to real number value, if the string begins with either’T’ or ’t’ then it returns true, and otherwise false.
When the column type is integer or real number, if the nearest integer of the cell value
reflected TZERO and TSCALn is zero, it returns false, otherwise true. If the argument is
NULL or invalid, it returns false. It returns false also when the cell value is as the sameas TNULLn value of ASCII table or integer type column of binary table.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().bvalue() returns the cell value.
EXAMPLES
See EXAMPLES in 12.8.20

12.8.23

table().col().svalue()

NAME
table().col().svalue() — Returns cell value as string

Ver. 1.2.1

187

SYNOPSIS
const char *table( ... ).col( ... ).svalue( long row_index );const char *table( ... ).col( ... ).svalue( long row_index,
const char *elem_name, long repetiti_idx = 0 );const char *table( ... ).col( ... ).svalue( long row_index,
long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().svalue() returns cell value as string.
As for string type column of binary table, and column of ASCII table whare TFORMn does not
represent numeric value, it returns string of cell which is formatted by TFORMn. If TFORMn is
not given, it returns raw cell string.
If the column of ASCII table does represent numeric value, it converts cell string to real
number value, and then converts it with TZEROn and TSCALn, and returns the value which isformatted as a string with TFORMn.
When TDISPn is given in the boolean column, it returns "T" , "F", or "U". When TDISPn isgiven, if the value is ’T’, then it formats 1 by TDISPn, and returns it. If the value is ’F’,
then it formats 0 by TDISPn, and returns it.
If the column type is integer or real number, it converts cell value with TZEROn and TSCALnof the header, and converts it to string and returns it. If TDISPn is specified, it converts with
TDISPn and returns it.
When the column type is integer, TZEROn is 0,TSCALn is 1.0, and no TDISPn is given, it
returns the string which is converted by format "%lld" of printf(). Otherwise, it converts
with the following printf format.
FITS::FLOAT_T
FITS::DOUBLE_T, FITS::LONGLONG_T
FITS::LONG_T
otherwise

...
...
...
...

"%G"
"%.15G"lll"%.10G""%.8G"

When the cell value is NULL or the argument is invalid, it returns string "NULL". Note that
there might be an space character padded for some given TDISPn. It also returns "NULL"
when the value of cell is TNULLn of ASCII table or integer type column of binary table. ThisNULL string value (default is "NULL") can be changed by table().assign null svalue() member
function (§12.8.29).
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)

188

SFITSIO User’s Reference Guide

RETURN VALUE
table().col().svalue() returns an address of string for cell value.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
See EXAMPLES of 12.8.20

12.8.24table().col().get svalue()

NAME
table().col().get svalue() — Returns cell value as string
SYNOPSIS
ssize_t table( ... ).col( ... ).get_svalue( long row_index,
char *dest_buf, size_t buf_size ) const;
ssize_t table( ... ).col( ... ).get_svalue( long row_index,
const char *elem_name,char *dest_buf, size_t buf_size ) const;
ssize_t table( ... ).col( ... ).get_svalue( long row_index,
const char *elem_name, long repetition_idx,
char *dest_buf, size_t buf_size ) const;
ssize_t table( ... ).col( ... ).get_svalue( long row_index,
long elem_index,
char *dest_buf, size_t buf_size ) const;
ssize_t table( ... ).col( ... ).get_svalue( long row_index,
long elem_index, long repetition_idx,
char *dest_buf, size_t buf_size ) const;
DESCRIPTION
table().col().get svalue() returns the cell value as string and store it to dest_buf.
When column of binary table is string type or when the TFORMn of column in ASCII table
does not represent numeric value, it returns string of cell which is formatted by TFORMn. If
TFORMn is not given, it returns raw cell string.
If the column of ASCII table does represent numeric value, it converts cell string to real
number value, and then converts it with TZEROn and TSCALn, and returns the value which isformatted as a string with TFORMn.
When TDISPn is given in the boolean column, it returns "T", "F", or "U". When TDISPn isgiven, If the value is ’T’, then it formats 1 by TDISPn, and returns it. If the value is ’F’,
then it formats 0 by TDISPn and returns it.
If the column type is integer or real number, it converts cell value with TZEROn and TSCALnof the header, and converts it to string and returns it. If TDISPn is specified, it converts with
TDISPn and returns it.
When the column type is integer, TZEROn is 0,TSCALn is 1.0, and no TDISPn is given, it
returns the string which is converted by format "%lld" of printf(). Otherwise, it converts
with the following printf format.

Ver. 1.2.1

189

FITS::FLOAT_T
FITS::DOUBLE_T, FITS::LONGLONG_T
FITS::LONG_T
otherwise

...
...
...
...

"%G"
"%.15G""%.10G""%.8G"

When the cell value is NULL or the argument is invalid, it returns string "NULL". Note that
there might be an space character padded for some given TDISPn. It also returns "NULL"
when the value of cell is TNULLn of ASCII table or integer type column of binary table. ThisNULL string value (default is "NULL") can be changed by table().assign null svalue() member
function (§12.8.29).
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I]
row_index[I]elem_name[I]elem_index[I]
repetiton_index[O] dest_buf[I]buf_size([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value (error)

row index
element nameelement index (the first dimension index of TDIMn)
second dimensional index
address of destination buffer
the size of dest_buf::

number of characters which is able to copy when the buffer
length is sufficient (excluding ’\0’).
the case when copy was not done because of invalid argument.

EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB (sli::err_rec).
EXAMPLES
char buf[128];
fits.table("EVENT").col("TIME").get_svalue( 0, buf, sizeof(buf) );12.8.25

table().col().assign()

NAME
table().col().assign() — Assign value to cell as real number
SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign( double value, long row_index );fits_table_col &table( ... ).col( ... ).assign( double value, long row_index,
const char *elem_name,long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign( double value, long row_index,
long elem_index, long repetition_idx = 0 );

190

SFITSIO User’s Reference Guide
fits_table_col &table( ... ).col( ... ).assign( float value, long row_index );fits_table_col &table( ... ).col( ... ).assign( float value, long row_index,
const char *elem_name,long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign( float value, long row_index,
long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign() reflects TZEROn and TSCALn to the given value of real number
value and assign the generated real number to the cell.
If value is NAN, it is handled as if NULL is given. In this case, if it has a TNULLn value in
integer type column of binary table or ASCII table, it assigns the value to the cell.
TZEROn and TSCALn value of header is valid when TFORMn of binary table includes ’B’, ’I’,
’J’, ’K’, ’E’, or ’D’, or , TFORMn of ASCII table includes ’I’, ’L’, ’F’, ’E’, ’G’, or ’D’.41)
If the column type is integer, it converts value with TZEROn and TSCALn and assigns thenearest integer to the cell.
When the column type is boolean, if the nearest integer to value is 0 then it assigns ’F’ tothe cell, and ’T’ otherwise. If NULL(NAN) is given, it assigns ’\0’.
When column of binary table is string type or when the TFORMn of column in ASCII table
does not represent numeric value, it converts with format "%.15G" of printf() ( when thevalue is double), or format "%G" of printf() ( when the value is float), and assigns thestring to the cell.
When the TFORMn of the column of ASCII table does represent numeric value, it converts
value with TZEROn and TSCALn, formats it with TFORMn, and assigns the formatted string.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
If the argument is invalid, it does not do anything.
PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : Input, [O] : Output)
RETURN VALUE
table().col().assign() returns a reference to the fits table col object.
EXCEPTION
When it fails to manipulate internal buffer, it raises exception derived from SLLIB (sli::err_rec)
41)

SFITSIO supports ’L’ and ’G’ which are not included in the definition of fits.

Ver. 1.2.1

191

EXAMPLES
double value = 0;
fits.table("EVENT").col("TIME").assign(value, 0);12.8.26

table().col().assign()

NAME
table().col().assign() — Assign value to cell as integer
SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign( int value, long row_index );fits_table_col &table( ... ).col( ... ).assign( int value, long row_index,
const char *elem_name,long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign( int value, long row_index,
long elem_index, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign( long value, long row_index );fits_table_col &table( ... ).col( ... ).assign( long value, long row_index,
const char *elem_name,long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign( long value, long row_index,
long elem_index, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign( long long value, long row_index );fits_table_col &table( ... ).col( ... ).assign( long long value, long row_index,
const char *elem_name,long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign( long long value, long row_index,
long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign() reflect TZEROn and TSCALn to integer value and assign the generated real number to the cell. NULL value cannot be given to these function.
In order to give NULL value, give double of float type NAN to argument of 12.8.25 functions.
TZEROn and TSCALn value of header is valid when TFORMn of binary table includes ’B’,’I’,’J’,’K’,’E’,or ’D’, or , TFORMn of ASCII table includes ’I’,’L’,’F’,’E’, ’G’, or ’D’.42)
If the column type is integer, it converts value with TZEROn and TSCALn and assigns thenearest integer to the cell.
42)

SFITSIO supports ’L’ and ’G’ which are not included in the definition of FITS.

192

SFITSIO User’s Reference Guide
When the column type is boolean, if the nearest integer to value is 0 then it assigns ’F’ tothe cell, and ’T’ otherwise.
When column of binary table is string type or when the TFORMn of column in ASCII table
does not represent numeric value, it converts with format "%lld" of printf(). If TFORMn is
specified, it additionally formats it.
If the TFORMn of the column in ASCII table does represent numeric value, it converts value
with TZEROn and TSCALn, formats it with TFORMn, and assign it to the cell.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins at zero.
If the argument is invalid, it does not do anything.

PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign() returns a reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB (sli::err_rec)
EXAMPLES
See the EXAMPLES at 12.8.25
12.8.27

table().col().assign()

NAME
table().col().assign() — Assign value to cell as string
SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign( const char *value, long row_index );fits_table_col &table( ... ).col( ... ).assign( const char *value, long row_index,
const char *elem_name,long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign( const char *value, long row_index,
long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign() assigns value to cell as string. If value is NULL or string "NULL"(You may insert spaces in the begining or end of the string) , then it is handled as if NULL

Ver. 1.2.1

193

was given. In this case, if it has a TNULLn value in integer type column of binary table or
ASCII table, it assigns the value to the cell. This NULL string value (default is "NULL")
can be changed by table().assign null svalue() member function (§12.8.29).
As for string type column of binary table, and column of ASCII table which TFORMn does not
represent numeric value, it returns string of cell which is formatted by TFORMn. If TFORMn
is not given, it returns raw cell string.
If the column of ASCII table does represent numeric value, it converts cell string to real
number value, and then converts it with TZEROn and TSCALn, and returns the value which
is formatted as a string with TFORMn. Since it converts string of cell by atof() of libc after
removing spaces, the string which can be converted is decimal integer, hex integer, or real
number value.
When type column type is boolean and the value can be converted to real number, it assigns’T’ if the value is not zero, ’F’ if the value is zero, and ’\0’ if the value is NAN. Whenthe value cannot be converted to real number, it assigns ’T’ if the value begins with ’T’
or ’t’, ’F’ if the value begins with ’F’ or ’f’, and ’\0’ otherwise.
When the column type is integer or real number, it converts value to real number, converts
it with TZEROn and TSCALn, and assigns it to the cell. If the column type is integer, it assigns
nearest integer.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins at zero.
if the argument is invalid, it does not do anything.
PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign() returns a reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB (sli::err_rec)
EXAMPLES
See the EXAMPLES at 12.8.25
12.8.28

table().col().convert type()

NAME
table().col().convert type() — Convert or modify data typeSYNOPSIS
fits_table_col &table( ... ).col( ... ).convert_type( int new_type );194

SFITSIO User’s Reference Guide
fits_table_col &table( ... ).col( ... ).convert_type( int new_type,
double new_zero );fits_table_col &table( ... ).col( ... ).convert_type( int new_type,
double new_zero,double new_scale );fits_table_col &table( ... ).col( ... ).convert_type( int new_type,
double new_zero,double new_scale,double new_null );DESCRIPTION
table().col().convert type() converts type of column which is integer or real number (in case that TFORMn includes ’B’, ’I’, ’J’, ’K’, ’E’, or ’D’) to new_type. It resizes the internal buffer if needed. The value available as new_type is FITS::DOUBLE_T,
FITS::FLOAT_T, FITS::LONGLONG_T, FITS::LONG_T, FITS::SHORT_T, or FITS::BYTE_T. If
new_zero, new_scale, new_null is given, it modifies TZEROn,TSCALn,TNULLn, and convert
the data which is reflect to them. Argument new_null is available only if new_type is integer
type.
String type column or boolean type column cannot be converted by this function.
PARAMETER[I] new_type
new type[I] new_zero
new TZERO value[I] new_scale new TSCAL value[I] new_null
new TNULL value([I] : input, [O] : output)
RETURN VALUE
table().col().convert type() returns a reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, table area reallocation failure when
expanding the table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
fits.table("EVENT").col("PIX_DATA").convert_type(FITS::DOUBLE_T);

12.8.29

table().assign null svalue()

NAME
table().assign null svalue() — Manipulate NULL string value (high level)
SYNOPSIS
fits_table &table( ... ).assign_null_svalue( const char *snull );DESCRIPTION
table().assign null svalue() assigns the high-level NULL string for table().col().svalue()(§12.8.23
table().col().assign()(§12.8.27).
The default value of NULL string is "NULL". You can change it using assign null svalue()member function.

Ver. 1.2.1

195

PARAMETER[I] snull NULL string value to set([I] : input, [O] : output)
RETURN VALUE
assign null svalue() returns the reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, table area reallocation failure when
expanding the table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).

12.8.30

table().col().tzero(), table().col().assign tzero()

NAME
table().col().tzero(), table().col().assign tzero() — Manipulate zero pointSYNOPSIS
double table( ... ).col( ... ).tzero() const;bool table( ... ).col( ... ).tzero_is_set() const;
fits_table_col &table( ... ).col( ... ).assign_tzero( double zero, int prec = 15 );fits_table_col &table( ... ).col( ... ).erase_tzero();DESCRIPTION
table().col().tzero() returns value of TZEROn.
table().col().assign tzero() assigns the value of TZEROn. prec indicates precision. If
prec is omitted then it write data to header record with 15 digit precision.
table().col().erase tzero() erases configuration of TZEROn.
PARAMETER[I] zero TZERO value to modify[I] prec precision (places)([I] : input, [O] : output)
RETURN VALUE
tzero() returns the value of TZEROn.
tzero is set() returns whether TZEROn is defined or not.
assign tzero() and erase tzero() returns the reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec)
EXAMPLES
if ( fits.table("EVENT").col("PIX_DATA").tzero_is_set() == false ) {fits.table("EVENT").col("PIX_DATA").assign_tzero(0.0);}

196

SFITSIO User’s Reference Guide

12.8.31table().col().tscal(), table().col().assign tscal()

NAME
table().col().tscal(), table().col().assign tscal() — Manipulate scaling factor
SYNOPSIS
double table( ... ).col( ... ).tscal() const;bool table( ... ).col( ... ).tscal_is_set() const;
fits_table_col &table( ... ).col( ... ).assign_tscal( double scal, int prec = 15 );fits_table_col &table( ... ).col( ... ).erase_tscal();DESCRIPTION
table().col().tscal() returns value of TSCALn.
table().col().assign tscal() assigns the value of TSCALn. prec indicates precision. If
prec is omitted then it write data to header record with 15 digit precision.
table().col().erase tscal() erases configuration of TSCALn.
PARAMETER[I] scal TSCAL value to modify[I] prec precision (places)([I] : input, [O] : output)
RETURN VALUE
tscal() returns the value of TSCALn.
tscal is set() returns whether TSCALn is defined or not.
assign tscal() and erase tscal() returns the reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, table area reallocation failure when
expanding the table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
if ( fits.table("EVENT").col("PIX_DATA").tscal_is_set() == false ) {fits.table("EVENT").col("PIX_DATA").assign_tscal(1.0);}
12.8.32

table().col().tnull(), table().col().assign tnull()

NAME
table().col().tnull(), table().col().assign tnull() — Manipulate NULL value
SYNOPSIS
long long table( ... ).col( ... ).tnull( const char **tnull_ptr = NULL ) const;bool table( ... ).col( ... ).tnull_is_set() const;
fits_table_col &table( ... ).col( ... ).assign_tnull( long long null );fits_table_col &table( ... ).col( ... ).erase_tnull();
DESCRIPTION
table().col().tnull() returns value of TNULLn. As for Ascii Table, and TNULL value ofstring is needed, it is able to get address of internal buffer by using tnull_ptr.
table().col().assign tnull() assigns the value of TNULLn.
table().col().erase tnull() erases configuration of TNULLn.

Ver. 1.2.1

197

PARAMETER[I]
null
TNULL value to set[O] tnull_ptr addres to string type TNULL value (Ascii Table only)([I] : input, [O] : output)
RETURN VALUE
tnull() returns the value of TNULLn.
tnull is set() returns whether TNULLn is defined or not.
assign tnull() and erase tnull() returns the reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, table area reallocation failure when
expanding the table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
if ( fits.table("EVENT").col("PIX_DATA").tnull_is_set() == false ) {fits.table("EVENT").col("PIX_DATA").assign_tnull(-1);}
12.8.33

table().col().tunit(), table().col().assign tunit()

NAME
table().col().tunit(), table().col().assign tunit() — Manipulate units of measurement
SYNOPSIS
const char *table( ... ).col( ... ).tunit() const;bool table( ... ).col( ... ).tunit_is_set() const;
fits_table_col &table( ... ).col( ... ).assign_tunit( const char *unit );fits_table_col &table( ... ).col( ... ).erase_tunit();DESCRIPTION
table().col().tunit() returns value of TUNITn.
table().col().assign tunit() assigns the value of TUNITn.
table().col().erase tunit() erases configuration of TUNITn.
PARAMETER[I] unit TUNIT value to modify([I] : input, [O] : output)
RETURN VALUE
tunit() returns the value of TUNITn.
tunit is set() returns whether TUNITn is defined or not.
assign tunit() and erase tunit() returns the reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, table area reallocation failure when
expanding the table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
if ( fits.table("EVENT").col("RA").tunit_is_set() == false ) {fits.table("EVENT").col("RA").assign_tunit("deg");}

198

SFITSIO User’s Reference Guide

12.8.34

table().init()

NAME
table().init() — Init table
SYNOPSIS
fits_table &table( ... ).init();fits_table &table( ... ).init( const fits::table_def defs[] );DESCRIPTION
table().init() erases all the contents of header and table and initialize it.
If defs is given, it creates column in accordance with it.
PARAMETER[I] defs fits::table_def structure([I] : input, [O] : output)
RETURN VALUE
table().init() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, there is no enough memory toallocate new table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
fits.table("EVENT").init();12.8.35

table().col().init()

NAME
table().col().init() — Init column
SYNOPSIS
fits_table_col &table( ... ).col( ... ).init();fits_table_col &table( ... ).col( ... ).init( const fits_table_col &src );DESCRIPTION
table().col().init() erases all the contents of the column and initialize it.
If src is given, it overwrites existing column with contents of src. Number of rows is notchanged by using this member function. Note that last some cells in src will not be copied
when number of rows of src is larger than that of destination table.
PARAMETER[I] src reference of source column object([I] : input, [O] : output)
RETURN VALUE
table().col().init() returns a reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, there is no enough memory toallocate new table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).

Ver. 1.2.1

199

EXAMPLESIn this code, the name of column “LON” of table “EVENT” will be updated to “RA”.
fits.table("EVENT").col("LON").init( fits_r.table("RAW").col("RA") );12.8.36

table().ascii to binary()

NAME
table().ascii to binary() — Convert ascii table to binary table
SYNOPSIS
fits_table &table( ... ).ascii_to_binary();
DESCRIPTION
If the attribute of table is ascii, then table().ascii to binary() converts it to binary.
If the attribute is converted to binary, the value of TFORMn in ascii table (tdisp member offits::table_def structure) is stored in the comment of TFORMn when saved as binary table.
TNULLn value is also stored in the comment (the value is undefined).
RETURN VALUE
table().ascii to binary() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB (sli::err_rec)
EXAMPLES
fits.table("X_CATALOG").ascii_to_binary();
12.8.37

table().assign col name()

NAME
table().assign col name() — Assign column name
SYNOPSIS
fits_table &table( ... ).assign_col_name( long col_index, const char *newname );fits_table &table( ... ).assign_col_name( const char *col_name, const char *newname );DESCRIPTION
table().assign col name() assigns column name to newname which specified by col_index
or col_name
PARAMETER[I] col_index column index[I] col_namecolumn name[I] newname
new column name([I] : input, [O] : output)
RETURN VALUE
table().assign col name() returns a reference of the fit table object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).

200

SFITSIO User’s Reference Guide

EXAMPLES
fits.table("EVENT").assign_col_name(0L, "TIME");12.8.38

table().define a col()NAME
table().define a col() — Modify column definition
SYNOPSIS
fits_table &table( ... ).define_a_col( long col_index,
const fits::table_def &def );fits_table &table( ... ).define_a_col( const char *col_name,const fits::table_def &def );DESCRIPTION
table().define a col() modifies definition of column specified by col_index or col_name.
Substitute NULL into members of def except to be modified.
PARAMETER[I] col_index column index[I] col_namecolumn name[I] defs
fits::table_def structure([I] : input, [O] : output)
RETURN VALUE
table().define a col() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, there is no enough memory toallocate new table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
fits::table_def def ={ "TIME","satellite time", NULL,NULL, "s","", "F16.3", "1D", "" };fits.table("EVENT").define_a_col(0L, def);

12.8.39

table().col header index()

NAME
table().col header index() — Index of header record for table column propertiesSYNOPSIS
long table( ... ).col_header_index( const char *col_name,const char *kwd ) const;
long table( ... ).col_header_index( long col_index,
const char *kwd ) const;
DESCRIPTION
table().col header index() returns an index of the fits header record object having keyword
prefix kwd such as TTYPE for the table column specified by col_index or col_name.

Ver. 1.2.1

201

PARAMETER[I] col_index Column index[I] col_name
Column name[I] kwd
Prefix of column keyword([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value::

Record index
Error (If specified keyword was not found.)

EXAMPLES
long idx = fits.table("EVENT").col_header_index("DATE", "TTYPE");12.8.40

table().col header()NAME
table().col header() — Reference of header record for table column propertiesSYNOPSIS
fits_header_record &table( ... ).col_header( const char *col_name,const char *kwd );fits_header_record &table( ... ).col_header( long col_index,
const char *kwd );const fits_header_record &table( ... ).col_header( const char *col_name,const char *kwd ) const;
const fits_header_record &table( ... ).col_header( long col_index,
const char *kwd ) const;
DESCRIPTION
table().col_header() returns reference of the fits header record object having keyword
prefix kwd such as TTYPE for the table column specified by col_index or col_name.
.svalue(), .dvalue(), .lvalue(), etc. can be used after .col_header(). See §12.4.4 andsucceeding sections for these member functions.
PARAMETER[I] col_index Column index[I] col_name
Column name[I] kwd
Prefix of column keyword([I] : input, [O] : output)
EXCEPTION
If the API fails to manipulate internal buffer (for example, there is no enough memory toallocate new table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception). If the read-only API does not found specified column keyword, it throws an
exception derived from SFITSIO.
EXAMPLES
printf("TTYPE of ’TIME’ = %s\n",fits.table("EVENT").col_header("TIME","TTYPE").svalue());

202
12.8.41

SFITSIO User’s Reference Guide
table().update col header()NAME
table().update col header() — Update a header recored of column propertiesSYNOPSIS
fits_table &table( ... ).update_col_header( const char *col_name,const char *kwd, const char *val, const char *com );fits_table &table( ... ).update_col_header( long col_index,
const char *kwd, const char *val, const char *com );DESCRIPTION
table().update_col_header() updates the fits header record object having keyword prefix
kwd such as TTYPE for the table column specified by col_index or col_name. Internal
properties in objects are updated simultaneously.
PARAMETER[I] col_index Column index[I] col_name
Column name[I] kwd
Prefix of column keyword[I] valValue of header record[I] com
Comment of header record([I] : input, [O] : output)
RETURN VALUE
table().update col header() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits.table("EVENT").update_col_header("TIME","TUNIT","s","unit");12.8.42

table().erase col header()NAME
table().erase col header() — Erase a header recored of column propertiesSYNOPSIS
fits_table &table( ... ).erase_col_header( const char *col_name,const char *kwd );fits_table &table( ... ).erase_col_header( long col_index,
const char *kwd );DESCRIPTION
table().erase_col_header() removes the fits header record object having keyword prefix
kwd such as TTYPE for the table column specified by col_index or col_name. Internal
properties in objects are updated simultaneously.
PARAMETER[I] col_index Column index[I] col_name
Column name[I] kwd
Prefix of column keyword([I] : input, [O] : output)

Ver. 1.2.1

203

RETURN VALUE
table().erase col header() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits.table("EVENT").erase_col_header("TIME","TUNIT");12.8.43

table().rename col header()NAME
table().rename col header() — Change keyword prefix of user-defined column headers
SYNOPSIS
fits_table &table( ... ).rename_col_header( const char *old_kwd,
const char *new_kwd );DESCRIPTIONThis member function changes keyword prefix of user-defined column headers from old_kwd
to new_kwd. Keywords defined in FITS standard (e.g., TTYPEn) cannot be changed.
PARAMETER[I] old_kwd Keyword prefix to be changed[I] old_kwd New keyword prefix([I] : input, [O] : output)
RETURN VALUE
table().rename col header() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLESThis code renames user-defined column keyword TLMAXn to TMMAXn.
fits.table("EVENT").rename_col_header("TLMAX","TMMAX");12.8.44

table().sort col header()NAME
table().sort col header() — Sort column header records
SYNOPSIS
fits_table &table( ... ).sort_col_header();
DESCRIPTION
table().sort col header() sorts all column header records in column order.
RETURN VALUE
table().sort col header() returns a reference to the fits table object.

204

SFITSIO User’s Reference Guide

EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits.table("EVENT").sort_col_header();

12.8.45

table().swap()

NAME
table().swap() — Swap table
SYNOPSIS
fits_table &table( ... ).swap( fits_table &obj );DESCRIPTION
table().swap() swaps the own content with that of obj.
PARAMETER[I/O] obj swap target object([I] : input, [O] : output)
RETURN VALUE
table().swap() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, there is no enough memory toallocate new table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
The following code swaps EVENT table and EVENT SAVE table of the fits object.
fits.table("EVENT").swap(fits.table("EVENT_SAVE"));12.8.46

table().append cols(), table().append a col()NAME
table().append cols(), table().append a col() — Append column
SYNOPSIS
fits_table &table( ... ).append_cols( const fits::table_def defs[] );fits_table &table( ... ).append_cols( fits_table &src );fits_table &table( ... ).append_a_col( const fits::table_def &def );fits_table &table( ... ).append_a_col( fits_table_col &src );DESCRIPTION
table().append cols() and table().append a col() append column to the table. append_cols()
appends multiple columns, append_a_col() appends single column.
If src is specified, not only column definition of src but also data area is copied. However,if there is not enough rows, not all rows are copied.

Ver. 1.2.1

205

PARAMETER[I] defs fits::table_def structure[I] src
object which has the column to be copied([I] : input, [O] : output)
RETURN VALUE
table().append cols() and table().append a col() return a reference to the fits tableobject.
EXCEPTION
If the API fails to manipulate internal buffer (for example, there is no enough memory toallocate new table), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec
exception).
EXAMPLES
const table_def &def = fits.table("EVENT").col(0L).definition();fits.table("EVENT_SAVE").append_a_col(def);

12.8.47

table().insert cols(), table().insert a col()NAME
table().insert cols(), table().insert a col() — Insert column
SYNOPSIS
fits_table &table( ... ).insert_cols( long index, const fits::table_def defs[]);fits_table &table( ... ).insert_cols( const char *col_name,const fits::table_def defs[] );fits_table &table( ... ).insert_cols( long index, fits_table &src );fits_table &table( ... ).insert_cols( const char *col_name, fits_table &src );fits_table &table( ... ).insert_a_col( long col_index,
const fits::table_def &def );fits_table &table( ... ).insert_a_col( const char *col_name,const fits::table_def &def );DESCRIPTION
table().insert cols() and table().insert a col() insert new column before column
specified by index or col_name. insert_cols() inserts multiple columns, and insert_a_col()inserts single columns.
If src is specified, not only column definition of src but also data area is copied. However,if there is not enough rows, not all rows are copied.
PARAMETER[I] index
column index to be inserted[I] col_name column name to be inserted[I] defs
fits::table_def structure[I] src
the column to be inserted([I] : input, [O] : output)
RETURN VALUE
table().insert cols() and table().insert a col() return a reference to the fits tableobject.

206

SFITSIO User’s Reference Guide

EXCEPTION
If the API fails to manipulate internal buffer (for example, there is no enough memory toinsert), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec exception).
EXAMPLES
fits::table_def def ={ "TIME_SAVE","saved time", NULL,NULL, "s","", "F16.3", "1D", "" };fits.table("EVENT").insert_a_col(1, def);
12.8.48table().swap cols()

NAME
table().swap cols() — Swap columns
SYNOPSIS
fits_table &table( ... ).swap_cols( long index0, long num_cols, long index1 );fits_table &table( ... ).swap_cols( const char *col_name0, long num_cols,
const char *col_name1 );DESCRIPTION
table().swap cols() swaps num_cols number of columns beginning with index0 or col_name0,
to num_cols number of columns beginning from index1 or col_name1.
If there is an overlap between two column groups, it decreases num_cols and do swap.
PARAMETER[I] index0
beginning column index (1)[I] col_name0 beginning column name (1)[I] num_cols
number of columns to swap
[I] index1
beginning column index (2)[I] col_name1 beginning column name (2)([I] : input, [O] : output)
RETURN VALUE
table().swap cols() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
The following code swaps column 0 and column 2.
fits.table("EVENT").swap_cols(0, 1, 2);
12.8.49

table().erase cols(), table().erase a col()NAME
table().erase a col() — Erase column
SYNOPSIS
fits_table &table( ... ).erase_cols( long index, long num_cols );fits_table &table( ... ).erase_cols( const char *col_name, long num_cols );fits_table &table( ... ).erase_a_col( long col_index );fits_table &table( ... ).erase_a_col( const char *col_name );Ver. 1.2.1

207

DESCRIPTION
table().erase cols() and table().erase a col() erase num_cols number of columns
which begins from index or col_name.
PARAMETER[I] index
begging column index to erase[I] col_name beginning column name to erase[I] num_cols number of columns to erase([I] : input, [O] : output)
RETURN VALUE
table().erase cols() and table().erase a col() returns a reference to the fits tableobject.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits.table("EVENT").erase_cols(0L, 1);

12.8.50

table().copy()

NAME
table().copy() — Copy column to other object
SYNOPSIS
void table( ... ).copy( fits_table *dest ) const;
void table( ... ).copy( long idx_begin, long num_rows, fits_table *dest ) const;
DESCRIPTION
table().copy() copies num_rows number of rows which begins from idx_begin, to dest
object.
If no index is given, it copies all rows.
This API is used to make temporary buffer which is given to import rows() (12.8.58)
PARAMETER[I]
idx_begin index of row with which it begins to copy[I]
num_rows
number of rows.
[O] dest
copy destination([I] : input, [O] : output)
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits_table tmp_buf;fits.table("EVENT").copy(0L,40, &tmp_buf);

208

SFITSIO User’s Reference Guide

12.8.51

table().resize rows()

NAME
table().resize rows() — Modify the number of rows in the table
SYNOPSIS
fits_table &table( ... ).resize_rows( long num_rows );DESCRIPTION
table().resize rows() modifies the number of rows in table to num_rows.
PARAMETER[I] num_rows number of rows([I] : input, [O] : output)
RETURN VALUE
table().resize rows() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, space allocation failure whenresizing), it throws an exception derived from SLLIB or SFITSIO (sli::err_rec exception).
EXAMPLES
fits.table("EVENT").resize_rows(100);
12.8.52

table().append rows(), table().append a row()

NAME
table().append rows(), table().append a row() — Append row to table
SYNOPSIS
fits_table &table( ... ).append_rows( long num_rows );fits_table &table( ... ).append_a_row();
DESCRIPTION
table().append rows() appends num_rows number of new rows to the end of table.
table().append a row() appends new single row to the end of table.
The new value of the appended row is 0 if the column type is integer or real number, ’\0’
if column type is boolean, ’ ’ if column type is string.
PARAMETER[I] num_rows number of rows to append([I] : input, [O] : output)
RETURN VALUE
table().append rows() and table().append a row() return a reference to the fits tableobject.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits.table("EVENT").append_rows(20);Ver. 1.2.1
12.8.53

209
table().insert rows(), table().insert a row()

NAME
table().insert rows(), table().insert a row() — Insert row to table
SYNOPSIS
fits_table &table( ... ).insert_rows( long index, long num_rows );fits_table &table( ... ).insert_a_row( long index );DESCRIPTION
table().insert rows() inserts num_rows number of new rows into the index-th row.
table().insert a row() inserts new single row into the index-th row.
The new value of the inserted row is 0 if the column type is integer or real number, ’\0’ ifcolumn type is boolean, ’ ’ if column type is string.
PARAMETER[I] index
index which the rows are inserted at[I] num_rows number of rows to be inserted([I] : input, [O] : output)
RETURN VALUE
table().insert rows() and table().insert a row() return a reference to the fits tableobject.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
The following code inserts 5 new rows in back of 10th row.
fits.table("EVENT").insert_rows(10, 5);
12.8.54

table().erase rows(), table().erase a row()

NAME
table().erase rows(), table().erase a row() — Erase row of table
SYNOPSIS
fits_table &table( ... ).erase_rows( long index, long num_rows );fits_table &table( ... ).erase_a_row( long index );DESCRIPTION
table().erase rows() erases num_rows number of rows starting from index-th row.
table().erase a row() erases index-th row.
PARAMETER[I] index
row index to be erased[I] num_rows number of rows to be erased([I] : input, [O] : output)
RETURN VALUE
table().erase rows() and table().erase a row() return a reference to the fits table object.

210

SFITSIO User’s Reference Guide

EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
The following codes erases 5 rows which begins from 10th row.
fits.table("EVENT").erase_rows(10, 5);
12.8.55

table().clean rows()

NAME
table().clean rows() — Initialize row of table
SYNOPSIS
fits_table &table( ... ).clean_rows();
fits_table &table( ... ).clean_rows( long index, long num_rows );DESCRIPTION
table().clean rows() initializes all the column of num_rows numbers of row starting fromindex-th row. If no argument is given, all the rows are initialized.
The initial value is 0 for integer and real number type column, ’\0’ for boolean type column,
and ’ ’ for string type column.
PARAMETER[I] index
the row index to be initialized[I] num_rows number of rows to be initialized([I] : input, [O] : output)
RETURN VALUE
table().clean rows() returns a reference to the fits table object.
EXAMPLES
The following codes initiates 5 rows from 10th row.
fits.table("EVENT").clean_rows(10, 5);
12.8.56

table().move rows()

NAME
table().move rows() — Copy rows
SYNOPSIS
fits_table &table( ... ).move_rows( long src_index, long num_rows, long dest_index );DESCRIPTION
table().move rows() copies the num_rows number of rows starting from src_index into
the dest_index.
PARAMETER[I] src_index
row index of source[I] num_rows
number of rows to be copied[I] dest_index row index of destination([I] : input, [O] : output)

Ver. 1.2.1

211

RETURN VALUE
table().move rows() returns a reference to the fits table object.
EXAMPLES
The following code copies 10th row into 11th row.
fits.table("EVENT").move_rows(10, 1, 11);12.8.57

table().swap rows()

NAME
table().swap rows() — Swap rows
SYNOPSIS
fits_table &table( ... ).swap_rows( long index0, long num_rows, long index1 );DESCRIPTION
table().swap rows() swaps the num_rows number of rows starting from index0 with index1.
If there is an overlap between two rows, it decreases num_cols and do swap.
PARAMETER[I] index0
the source row index to be swapped[I] num_rows number of rows to be swapped[I] index1
the destination row index to be swapped([I] : input, [O] : output)
RETURN VALUE
table().swap rows() returns a reference to the fits table object.
EXAMPLES
The following code swaps 10th row with 11th row.
fits.table("EVENT").swap_rows(10, 1, 11);12.8.58

table().import rows()

NAME
table().import rows() — Import table
SYNOPSIS
fits_table &table( ... ).import_rows( long dest_index, bool match_by_name,const fits_table &from,long idx_begin = 0,long num_rows = FITS::ALL );DESCRIPTION
table().import rows() imports num_rows number of rows starting from idx_begin of tableobject ‘from‘ into num_rows number of rows specified by dest_index. All the columns areimported.
How to allocate each of columns on ’from’ to the object is decided by match_by_name. Whenmatch_by_name is true, it searches the column of which the names are identical and imports
the column. When match_by_name is false, it imports from the 0th column in order.
The column type of ‘from‘ table and column type of the object does not need to be identical.
If two column types are not identical, it converts the type and imports.

212

SFITSIO User’s Reference Guide

PARAMETER[I] dest_index
destination row index to be imported[I] match_by_name the flag whether it matches by column name[I] from
source table object to import from
[I] idx_begin
source row index to be imported[I] num_rows
number of rows([I] : input, [O] : output)
RETURN VALUE
table().import rows() returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits.table("EVENT").import_rows( 0, false, fits.table("EVENT_SAVE") );12.8.59

table().col().move()

NAME
table().col().move() — Copy row into row in particular column
SYNOPSIS
fits_table_col &table( ... ).col( ... ).move( long src_index, long num_rows, long dest_index );DESCRIPTION
In a particular column, table().col().move() copies num_rows number of rows startingfrom src_index into dest_index.
PARAMETER[I] src_index
source index[I] num_rows
number of columns[I] dest_index destination index([I] : input, [O] : output)
RETURN VALUE
table().col().move() returns a reference to the fits table col object.
EXAMPLES
The following code copies 0th row to 2nd row at column 0.
fits.table("EVENT").col(0L).move( 0, 1, 2 );12.8.60

table().col().swap()

NAME
table().col().swap() — Swap rows at particular column
SYNOPSIS
fits_table_col &table( ... ).col( ... ).swap( long index0, long num_rows, long index1 );Ver. 1.2.1

213

DESCRIPTIONAs for specified column, table().col().swap() swap num_rows number of rows startingfrom index0 with rows starting from index1.
If there is an overlap between two rows, it decreases num_cols and do swap.
PARAMETER[I] index0
source row index[I] num_rows number of rows
[I] index1
destination index([I] : input, [O] : output)
RETURN VALUE
table().col().swap() returns reference to the fits table col object.
EXAMPLES
The following code swaps 0th row with 2nd row at column 0.
fits.table("EVENT").col(0L).swap( 0, 1, 2 );12.8.61

table().col().clean()

NAME
table().col().clean() — Initialize value at specified column
SYNOPSIS
fits_table_col &table( ... ).col( ... ).clean();fits_table_col &table( ... ).col( ... ).clean( long index, long num_rows );DESCRIPTIONAs for specified column, table().col().clean() initializes num_rows number of rows starting from index. If no argument is given, all the rows are initialized.
The initial value is 0 for integer and real number type column, ’\0’ for boolean type column,
and ’ ’ for string type column.
PARAMETER[I] index
starting index to initialize[I] num_rows number of rows([I] : input, [O] : output)
RETURN VALUE
table().col().clean() returns a reference to the fits table col object.
EXAMPLES
fits.table("EVENT").col(0L).clean();

12.8.62

table().col().import()

NAME
table().col().import() — Import from particular column

214

SFITSIO User’s Reference GuideSYNOPSIS
fits_table_col &table( ... ).col( ... ).import( long dest_index,
const fits_table_col &from,long idx_begin = 0,long num_rows = FITS::ALL );DESCRIPTION
table().col().clean() imports num_rows number of rows of which the index begins with
idx_begin on the table object ’from’ into num_rows number of rows of which the index
begins with dest_index.
The column type of ‘from‘ table and column type of the object does not need to be identical.
If two column types are not identical, it converts the type and imports.
PARAMETER[I] dest_index destination row index to be imported[I] from
source table object to import from
[I] idx_begin
source row index to be imported[I] num_rows
number of rows([I] : input, [O] : output)
RETURN VALUE
table().col().import() returns a reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB or
SFITSIO (sli::err_rec exception).
EXAMPLES
fits.table("EVENT").col(0L).import( 0, fits.table("EVENT_SAVE").col(0L) );12.8.63table().col().assign default()

NAME
table().col().assign default() — Specify a value to be set for new cells when resizing rows
SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_default( double value );fits_table_col &table( ... ).col( ... ).assign_default( float value );fits_table_col &table( ... ).col( ... ).assign_default( long long value );fits_table_col &table( ... ).col( ... ).assign_default( long value );fits_table_col &table( ... ).col( ... ).assign_default( int value );fits_table_col &table( ... ).col( ... ).assign_default( const char *value );fits_table_col &table( ... ).col( ... ).assign_default_value( const void *value_ptr );DESCRIPTION
Using these member functions, programmers can specify a value to be set for new cells createdby table().resize rows(), etc.
.assign default() is a high-level API, and the value of argument is converted into theappropriate value which is reflected by the values of TZERO, TSCALE and TNULL in the header.
Set NAN to the argument to specify NULL value.

Ver. 1.2.1

215.assign default value() is a low-level API, and values of TZERO, etc. are not referred.
Programmers should set an address of a value whose type is that of image of current object.
PARAMETER[I] value
a value to be set for new cells[I] value_ptr an address of a value to be set for new cells([I] : input, [O] : output)
RETURN VALUE
These member functions returns a reference to the modified fits table col object.
EXCEPTION
If the API fails to allocate internal memory, it throws an exception derived from SLLIB(sli::err_rec
exception).
EXAMPLES
Next code specifies NULL value to be set for new cells in first column, and resizes the lengthof rows.
fits.table("EVENT").col(0L).assign_default(NAN);
fits.table("EVENT").resize_rows(100);

12.9

Lower level manipulation of Ascii Table HDU and Binary TableIn this section, we describe lower level API to manipulate ASCII Table HDU and Binary Table
HDU. As for lower level API, converting with TZEROn, TSCALn of header must be done by user’shand. Usually, the APIs in this section is not necessary, but maybe useful for the performancetuning.
12.9.1

table().col().data array cs()

NAME
table().col().data array cs() — Reference to data buffer management object
SYNOPSIS
const sli::mdarray &table( ... ).col( ... ).data_array_cs() const;
DESCRIPTION
The image buffer of fits table col class is managed by mdarray class of SLLIB. data array cs
function is used when user wants to calculate with mdarray class.
For the detail of mdarray class, See SLLIB manual.

12.9.2

table().col().data ptr()

NAME
table().col().data ptr() — Address of the data buffer inside the object
SYNOPSIS
void *table( ... ).col( ... ).data_ptr();

216

SFITSIO User’s Reference Guide

DESCRIPTION
table().col().data ptr() returns the address of the internal table data buffer.
The returned value is the address of internal buffer of the object, so it will be invalid when
the object was destroyed or the type or size was changed.
Use the returned address to be cast to a pointer type, corresponding to the current column
type, which is choosed from fits::double_t *, fits::float_t *, fits::longlong_t *,fits::long_t *, fits::short_t *, fits::byte_t * or fits::logical_t *.
RETURN VALUE
table().col().data ptr() returns an address of the internal table data buffer.
EXAMPLES
fits::double_t *tbl_data_ptr= (fits::double_t *)fits.table("EVENT").col(0L).data_ptr();::12.9.3

table().col().get data()

NAME
table().col().get data() — Copy data to external buffer
SYNOPSIS
ssize_t *table( ... ).col( ... ).get_data( void *dest_buf, size_t buf_size ) const;
ssize_t *table( ... ).col( ... ).get_data( long row_idx,
void *dest_buf, size_t buf_size ) const;
DESCRIPTION
table().col().get data() copies the raw column data from the row_idx, maximum of
buf_size byte, to dest_buf.
Use the address specified with dest_buf to be cast to a pointer type, corresponding to
the current column type, which is choosed from fits::double_t *, fits::float_t *,fits::longlong_t *, fits::long_t *, fits::short_t *, fits::byte_t * or fits::logical_t *.
PARAMETER[O] dest_buf the address of destination buffer[I]buf_size size of dest_buf[I]
row_idx
the starting row index to get data([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value (error)::

byte length which is able to copy when the buffer length issufficient.
the case when copy was not done because of invalid argument.

EXAMPLES
fits_table_col &col_ref = fits.table("EVENT").col(0L);size_t buf_size = col_ref.elem_byte_length() * col_ref.length();char *dest_buf = (char *)malloc(buf_size);if ( dest_buf == NULL ) {Ver. 1.2.1

217/* Error Handling */}col_ref.get_data(dest_buf, buf_size);

12.9.4

table().col().put data()

NAME
table().col().put data() — Input the data from external buffer
SYNOPSIS
ssize_t *table( ... ).col( ... ).put_data( const void *src_buf, size_t buf_size );ssize_t *table( ... ).col( ... ).put_data( long row_idx, const void *src_buf, size_t buf_size );DESCRIPTION
table().col().put data() copies the raw data of src_buf from the row_idx th row withmaximum of buf_size, to the internal buffer of the object.
PARAMETER[I] src_buf
the address of source buffer[I] buf_size size of src_buf[I] row_idx
the starting row index to copy([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value (error)::

byte length which can be copied when the buffer length of
src_buf is sufficient.
the case when copy was not done because of invalid argument.

EXAMPLES
Following code modifies all the contents of the column 0 in the table “EVENT” in user’s
buffer.
fits_table_col &col_ref = fits.table("EVENT").col(0L);size_t buf_size = col_ref.elem_byte_length() * col_ref.length();char *data_buf = (char *)malloc(buf_size);::
col_ref.put_data(data_buf, buf_size);

12.9.5table().heap ptr()

NAME
table().heap ptr() — Address of the heap buffer in the object
SYNOPSIS
void *table( ... ).heap_ptr();
DESCRIPTION
table().heap ptr() returns the address of the internal table heap buffer for variable length
array.

218

SFITSIO User’s Reference Guide
The data in heap buffer are stored with big-endian, and the alignment of the data is notdefined. Therefore, copying byte data from heap area in objects into programmer’s buffer
and adjustment of endianness is required when reading variable length array of a row. When
writing data into heap buffer, the opposite procedure is needed.
The returned value is the address of internal buffer of the object, so it will be invalid when
the object was destroyed or the size was changed.
Using table().get heap() and table().put heap() is recommended for general purposes. See
also §12.9.6 and §12.9.7.

12.9.6table().get heap()

NAME
table().get heap() — Copy heap data to external buffer
SYNOPSIS
ssize_t *table( ... ).get_heap( void *dest_buf, size_t buf_size ) const;
ssize_t *table( ... ).get_heap( long offset,
void *dest_buf, size_t buf_size ) const;
DESCRIPTION
table().get heap() copies the data in the heap buffer (for variable length array) from theoffset, maximum of buf_size byte, to dest_buf.
The data in the heap buffer are stored with big-endian, therefore, programmer’s buffer pointed
by dest_buf can be read after endianness adjustment.
PARAMETER[O] dest_buf the address of destination buffer[I]buf_size size of dest_buf[I]offsetthe starting position (byte offset) in heap to get data([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value (error)::

byte length which is able to copy when the buffer length issufficient.
the case when copy was not done because of invalid argument.

EXAMPLES
See test/access bte heap.cc in SFITSIO source package.
12.9.7table().put heap()

NAME
table().put heap() — Input the heap data from external buffer
SYNOPSIS
ssize_t *table( ... ).put_heap( const void *src_buf, size_t buf_size );ssize_t *table( ... ).put_heap( long offset,
const void *src_buf, size_t buf_size );DESCRIPTION
table().put heap() copies the data of src_buf with maximum of buf_size, to the internal
heap buffer of the object at the position (byte offset) specified by offset.
The data in src_buf have to become big-endian before using .put_heap().

Ver. 1.2.1

219

PARAMETER[I] src_buf
the address of source buffer[I] buf_size size of src_buf[I] offset
the starting position (byte offset) in heap to copy([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value (error)::

byte length which can be copied when the buffer length of
src_buf is sufficient.
the case when copy was not done because of invalid argument.

EXAMPLES
See sample/create vl array.cc in SFITSIO source package.

12.9.8table().resize heap()

NAME
table().resize heap() — Update size of heap area
SYNOPSIS
fits_table &table( ... ).resize_heap( size_t sz );DESCRIPTIONThis member function updates size of the heap buffer in the object. Set argument sz inbytes.
RETURN VALUEThis member functions returns a reference to the fits table object.
EXCEPTION
If the API fails to manipulate internal buffer, it throws an exception derived from SLLIB (sli::err_rec)
EXAMPLES
See sample/create vl array.cc in SFITSIO source package.

12.9.9table().reverse heap endian()

NAME
table().reverse heap endian() — Reverse endian of specified data in heap area
SYNOPSIS
fits_table &table( ... ).reverse_heap_endian( long offset,
int type, long length );DESCRIPTIONThis member function reverses the endian of an array that begins at offset (0-indexed, in
bytes) in heap area, when endian conversion is required. Data type and length of it are
specified by arguments type and length.
Argument type can take FITS::SHORT_T, FITS::LONG_T, FITS::LONGLONG_T, FITS::FLOAT_T,
FITS::DOUBLE_T, FITS::COMPLEX_T or FITS::DOUBLECOMPLEX_T.
Note that this member function performs the endian conversion only for little-endian machines.

220

SFITSIO User’s Reference Guide

PARAMETER[I] offset the starting position (byte offset) in heap buffer[I] type
type of data elements[I] length number of data elements([I] : input, [O] : output)
RETURN VALUEThis member functions returns a reference to the fits table object.

12.9.10table().reserved area length()

NAME
table().reserved area length() — Length of reserved area in data unit
SYNOPSIS
long long table( ... ).reserved_area_length() const;
DESCRIPTIONThis member function returns byte length of reserved area in the data unit of the binary
table HDU.
See §3.5 for details of reserved area.

12.9.11table().resize reserved area()

NAME
table().resize reserved area() — Change byte length of reserved area
SYNOPSIS
fits_table &table( ... ).resize_reserved_area( long long sz );DESCRIPTIONThis member function changes length of reserved area in the data unit of the binary table
HDU. Set the length to sz in bytes.
See §3.5 for details of reserved area.
RETURN VALUEThis member functions returns a reference to the fits table object.

12.9.12table().col().short value()

NAME
table().col().short value() — Return the raw value of a cell as integer (short type)SYNOPSIS
short table( ... ).col( ... ).short_value( long row_index ) const;
short table( ... ).col( ... ).short_value( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
short table( ... ).col( ... ).short_value( long row_index,
long elem_index, long repetition_idx = 0 ) const;

Ver. 1.2.1

221

DESCRIPTION
table().col().short value() returns the raw value of a cell as integer (short type). Thisfunction can access the value fastest when the column type is FITS::SHORT_T (includes ’I’
in TFORMn). However, the value returned by these functions does not reflect TZEROn or
TSCALn.
If the column type is real number, it returns the rounded value.
When type column type is boolean, it returns 1 if the value is ’T’, and 0 otherwise.
If the column type is string, it converts the value to real number, and returns the roundedvalue.
To specify row, use row_index. To specify element, use elem_name or elem_index.
For elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().short value() returns the cell value.
EXAMPLES
short value = fits.table("EVENT").col(0L).short_value(0);::12.9.13table().col().long value()

NAME
table().col().long value() — Returns the raw cell value as integer (long type)SYNOPSIS
long table( ... ).col( ... ).long_value( long row_index ) const;
long table( ... ).col( ... ).long_value( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
long table( ... ).col( ... ).long_value( long row_index,
long elem_index, long repetition_idx = 0 ) const;
DESCRIPTION
table().col().long value() returns the raw value of a cell as integer (long type). Thisfunction can access the value fastest when the column type is FITS::LONG_T (includes ’J’
in TFORMn). However, the value returned by these functions does not reflect TZEROn or
TSCALn.
If the column type is real value, it returns the rounded value.
When the column type is boolean, it returns 1 if the value is ’T’, and 0 otherwise.

222

SFITSIO User’s Reference Guide
If the column type is string, it converts the value to real number, and returns the roundedvalue.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.

PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().long value() returns the cell value.
EXAMPLES
See EXAMPLES of 12.9.12

12.9.14table().col().longlong value()

NAME
table().col().longlong value() — Returns the raw value of a cell as integer (long long type)SYNOPSIS
long long table( ... ).col( ... ).longlong_value( long row_index ) const;
long long table( ... ).col( ... ).longlong_value( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
long long table( ... ).col( ... ).longlong_value( long row_index,
long elem_index, long repetition_idx = 0 ) const;
DESCRIPTION
table().col().longlong value() returns the raw value of a cell as integer (long long type).
This function can access the value fastest when the column type is FITS::LONGLONG_T (includes ’K’ in TFORMn). However, the value returned by these functions does not reflect
TZEROn or TSCALn.
If the column type is real value, it returns the rounded value.
When the column type is boolean, it returns 1 if the value is ’T’, and 0 otherwise.
If the column type is string, it converts the value to real number, and returns the roundedvalue.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.

Ver. 1.2.1

223

PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().longlong value() returns the cell value.
EXAMPLES
See EXAMPLES of 12.9.12
12.9.15

table().col().byte value()

NAME
table().col().byte value() — Returns raw cell value as integer (byte type)SYNOPSIS
unsigned char table( ... ).col( ... ).byte_value( long row_index ) const;
unsigned char table( ... ).col( ... ).byte_value( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
unsigned char table( ... ).col( ... ).byte_value( long row_index,
long elem_index, long repetition_idx = 0 ) const;
DESCRIPTION
table().col().byte value() returns the raw value of a cell as integer (byte type). Thisfunction can access the value fastest when the column type is FITS::BYTE_T (includes ’B’
in TFORMn). However, the value returned by these functions does not reflect TZEROn or
TSCALn.
If the column type is real value, it returns the rounded value.
When the column type is boolean, it returns 1 if the value is ’T’, and 0 otherwise.
If the column type is string, it converts the value to real number, and returns the roundedvalue.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().byte value() returns the cell value.
EXAMPLES
See EXAMPLES of 12.9.12

224

SFITSIO User’s Reference Guide

12.9.16table().col().float value()

NAME
table().col().float value() — Returns the raw cell value as real number (float type)SYNOPSIS
float table( ... ).col( ... ).float_value( long row_index ) const;
float table( ... ).col( ... ).float_value( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
float table( ... ).col( ... ).float_value( long row_index,
long elem_index, long repetition_idx = 0 ) const;
DESCRIPTION
table().col().float value() returns the raw cell value as real number (float type). Thisfunction can access the value fastest when the column type is FITS::FLOAT_T (includes ’E’
in TFORMn). However, the value returned by these functions does not reflect TZEROn or
TSCALn.
If the column type is boolean, it returns 1 if the value is ’T’, and 0 otherwise.
If the column type is string, it converts the value to real number, and returns it.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().float value() returns the cell value.
EXAMPLES
See EXAMPLES of 12.9.12

12.9.17table().col().double value()

NAME
table().col().double value() — Returns the raw cell value as real number (double type)SYNOPSIS
double table( ... ).col( ... ).double_value( long row_index ) const;
double table( ... ).col( ... ).double_value( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
double table( ... ).col( ... ).double_value( long row_index,
long elem_index, long repetition_idx = 0 ) const;

Ver. 1.2.1

225

DESCRIPTION
table().col().double value() returns the raw cell value as real number (double type).
This function can access the value fastest when the column type is FITS::DOUBLE_T (includes’D’ in TFORMn). However, the value returned by these functions does not reflect TZEROnor TSCALn.
If the column type is boolean, it returns 1 if the value is ’T’, and 0 otherwise.
If the column type is string, it converts the value to real number, and returns it.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().double value() returns the cell value.
EXAMPLES
See EXAMPLES of 12.9.12
12.9.18

table().col().bit value()

NAME
table().col().bit value() — Returns raw cell value as integer (bit type)SYNOPSIS
long table( ... ).col( ... ).bit_value( long row_index ) const;
long table( ... ).col( ... ).bit_value( long row_index,
const char *elem_name, long repetition_idx = 0, int nbit = 0 ) const;
long table( ... ).col( ... ).bit_value( long row_index,
long elem_index, long repetition_idx = 0, int nbit = 1 ) const;
DESCRIPTION
table().col().bit value() returns the raw cell value as integer (bit type). This function
can access the value fastest when the column type is FITS::BIT_T (includes ’X’ in TFORMn).
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
Argument nbit indicates how many bits to the right from specified element. If nbit is zero,
bit-field description specified with TELEMn, which is counted from specified element to theright, is used. See also §10.10 for bit-field description.
If the column type is real number, it returns the rounded value. However, the value returnedby these functions does not reflect TZEROn or TSCALn.

226

SFITSIO User’s Reference Guide
When the column type is boolean, it returns 1 if the value is ’T’, and 0 otherwise.
If the column type is string, it converts the value to real number, and returns the roundedvalue.
The index begins with zero.

PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().bit value() returns the cell value.
EXAMPLES
See EXAMPLES of 12.9.12
12.9.19

table().col().logical value()

NAME
table().col().logical value() — Return row cell value as boolean
SYNOPSIS
int table( ... ).col( ... ).logical_value( long row_index ) const;
int table( ... ).col( ... ).logical_value( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
int table( ... ).col( ... ).logical_value( long row_index,
long elem_index, long repetition_idx = 0 ) const;
DESCRIPTION
table().col().logical value() returns raw call value as boolean. The returned value
is ’T’, ’F’, or ’U’. This function can access the value fastest when the column type is
FITS::LOGICAL_T (includes ’L’ in TFORMn).
When the type of column is boolean, it returns ’T’ if the value is ’T’, ’F’ if the value is’F’, and ’U’ otherwise.
If type column type is string, it converts string to real number, rounds it, and if the result
is 0 then it returns ’F’ , and ’T’ otherwise. When the string cannot be converted to real
number, if the string begins with ’T’ or ’t’ then it returns ’T’, if it begins with ’F’ or ’f’
then it returns ’F’, and ’U’ otherwise.
When the column type is real number, it rounds the value, and if the value is 0 then it returns’F’ and ’T’ otherwise. When the column type is integer, if the value is 0 then it returns’F’, and ’T’ otherwise. However, the value returned by these functions does not reflect
TZEROn or TSCALn.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.

Ver. 1.2.1

227

PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().logical value() returns the cell value.
EXAMPLES
See EXAMPLES of 12.9.12
12.9.20

table().col().string value()

NAME
table().col().string value() — Returns raw cell value as string
SYNOPSIS
const char *table( ... ).col( ... ).string_value( long row_index ) const;
const char *table( ... ).col( ... ).string_value( long row_index,
const char *elem_name, long repetition_idx = 0 ) const;
const char *table( ... ).col( ... ).string_value( long row_index,
long elem_index, long repetition_idx = 0 ) const;
DESCRIPTION
table().col().string value() returns the raw cell value as string. This function canaccess the value fastest when the column type is FITS::ASCII_T (includes ’A’ in TFORMn).
If the column type is string, it returns the raw string.
If the column type is boolean, it returns whether "T", "F", or "U".
If the column type is integer, it returns the "%lld" formatted string of libc’s printf. If thecolumn type is real number, it returns the "%.15G" formatted string of libc’s printf. However,the value returned by these functions does not reflect TZEROn or TSCALn.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().string value() returns an address of the string of cell value.
EXAMPLES
See EXAMPLES of 12.9.12

228

SFITSIO User’s Reference Guide

12.9.21

table().col().array heap offset()

NAME
table().col().array heap offset() — Returns address of byte data in the heap area
SYNOPSIS
long table( ... ).col( ... ).array_heap_offset( long row_index,
long elem_index = 0 ) const;
DESCRIPTION
On specified column having variable length array(s), this member function returns an addressof the byte data on the heap area referred by specified row.
When a row refers multiple variable length arrays, set elem index to select one from them.
The index begins with zero.
Use .array_length() to obtain length of variable length array(s). See §12.8.18 for it.
PARAMETER[I] row_index
row index[I] elem_index index of array to be selected (can be omitted)([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value (error)::

0-indexed address (in bytes) on the heap area.
the case when invalid arguments are set, specified column does
not refer heap area, etc.

EXAMPLES
See test/access_bte_heap.cc in SFITSIO source package.
12.9.22

table().col().get string value()

NAME
table().col().get string value() — Gets the raw cell value as string
SYNOPSIS
ssize_t table( ... ).col( ... ).get_string_value( long row_index,
char *dest_buf, size_t buf_size ) const;
ssize_t table( ... ).col( ... ).get_string_value( long row_index,
const char *elem_name,char *dest_buf, size_t buf_size ) const;
ssize_t table( ... ).col( ... ).get_string_value( long row_index,
const char *elem_name, long repetition_idx,
char *dest_buf, size_t buf_size ) const;
ssize_t table( ... ).col( ... ).get_string_value( long row_index,
long elem_index,
char *dest_buf, size_t buf_size ) const;
ssize_t table( ... ).col( ... ).get_string_value( long row_index,
long elem_index, long repetition_idx,
char *dest_buf, size_t buf_size ) const;
DESCRIPTION
table().col().get string value() converts raw cell value to string and stores it to dest_buf.
The buffer size (in bytes) is specified with buf_size.

Ver. 1.2.1

229

If the column type is string then raw string is stored.
If type column type is boolean and no TDISPn is given, it returns "T", "F", or "U".
If the column type is integer, it stores the "%lld" formatted string of libc’s printf. If thecolumn type is real number, it stores the "%.15G" formatted string of libc’s printf. However,the value stored by these functions does not reflect TZEROn or TSCALn.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index. The index begins withzero.
PARAMETER[I]
row_index[I]elem_name[I]elem_index[I]
repetiton_index[O] dest_buf[I]buf_size([I] : input, [O] : output)
RETURN VALUE
Non-negative value
Negative value (error)

row index
element nameelement index (the first dimension index of TDIMn)
second dimensional index
destination buffer
size of dest_buf::

number of characters which can be copied when the buffer
length is sufficient (excluding ’\0’).
the case when copy was not done because of invalid argument.

EXCEPTION
If the API fails to allocate internal memory area, it throws an exception of SFITSIO (sli::err_rec)
EXAMPLES
char buf[128];
fits.table("EVENT").col(0L).get_string_value( 0, buf, sizeof(buf) );12.9.23

table().col().assign short()

NAME
table().col().assign short() — Assign value to the cell directly as integer (short type)SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_short( short value,long row_index );fits_table_col &table( ... ).col( ... ).assign_short( short value,long row_index, const char *elem_name, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign_short( short value,long row_index, long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign short() assigns value to the cell directly as integer (short type).
This function can access the value fastest when the column type is FITS::SHORT_T (includes’I’ in TFORMn). However, these functions does not convert the value by TZEROn and
TSCALn of header.
When the column type is boolean, it stores ’F’ if the value is 0, and ’T’ otherwise.

230

SFITSIO User’s Reference Guide
If the column type is string, it formats the value with "%hd" of printf(), and stores it.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.

PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign short() returns reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, value formatting failure), it
throws an exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
short value = 0;
fits.table("EVENT").col(0L).assign_short(value, 0);12.9.24table().col().assign long()

NAME
table().col().assign long() — Assign value to the cell directly as integer (long type)SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_long( long value,long row_index );fits_table_col &table( ... ).col( ... ).assign_long( long value,long row_index, const char *elem_name, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign_long( long value,long row_index, long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign long() assigns value to the cell directly as integer (long type). Thisfunction can access the value fastest when the column type is FITS::LONG_T (includes ’J’
in TFORMn). However, these functions does not convert the value by TZEROn and TSCALnof header.
When the column type is boolean, it stores ’F’ if the value is 0, and ’T’ otherwise.
If the column type is string, it stores the "%ld" formatted string of printf().
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.

Ver. 1.2.1

231

PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign long() returns reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, value formatting failure), it
throws an exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
See EXAMPLES of 12.9.23
12.9.25

table().col().assign longlong()

NAME
table().col().assign longlong() — Assign value to the cell directly as integer (long long type)SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_longlong( long long value,long row_index );fits_table_col &table( ... ).col( ... ).assign_longlong( long long value,long row_index, const char *elem_name, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign_longlong( long long value,long row_index, long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign longlong() assigns value to the cell directly as integer (long logtype). This function can access the value fastest when the column type is FITS::LONGLONG_T(includes ’K’ in TFORMn). However, these functions does not convert the value by TZEROn
and TSCALn of header.
When the column type is boolean, it stores ’F’ if the value is 0, and ’T’ otherwise.
If the column type is string, it stores the "%lld" formatted string of printf().
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] value
the value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)

232

SFITSIO User’s Reference Guide

RETURN VALUE
table().col().assign longlong() returns reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, value formatting failure), it
throws an exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
See EXAMPLES of 12.9.23
12.9.26

table().col().assign byte()

NAME
table().col().assign byte() — Assign value to the cell directly as integer (byte type)SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_byte( unsigned char value,long row_index );fits_table_col &table( ... ).col( ... ).assign_byte( unsigned char value,long row_index, const char *elem_name, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign_byte( unsigned char value,long row_index, long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign byte() assigns value to the cell directly as integer (byte type). Thisfunction can access the value fastest when the column type is FITS::BYTE_T (includes ’B’
in TFORMn). However, these functions does not convert the value by TZEROn and TSCALnof header.
When the column type is boolean, it stores ’F’ if the value is 0, and ’T’ otherwise.
If the column type is string, it formats the value with "%hhu" of printf(), and stores it.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] value
value to store[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign byte() returns reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, value formatting failure), it
throws an exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
See EXAMPLES of 12.9.23

Ver. 1.2.1
12.9.27

233
table().col().assign float()

NAME
table().col().assign float() — Assign value to the cell directly as real number (float type)SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_float( float value,long row_index );fits_table_col &table( ... ).col( ... ).assign_float( float value,long row_index, const char *elem_name, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign_float( float value,long row_index, long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign float() assigns value to the cell directly as real number (floattype). This function can access the value fastest when the column type is FITS::FLOAT_T(includes ’E’ in TFORMn). However, these functions does not convert the value by TZEROn
and TSCALn of header.
If the column type is integer, it stores the rounded value.
When the column type is boolean, it rounds the value, and if the value is 0 then stores ’F’,
and ’T’ otherwise.
If the column type is string, it formats with "%.15G" of printf() and stores it.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign float() returns reference to the fits table col object.
EXCEPTION
If the API fails to manipulate internal buffer (for example, value formatting failure), it
throws an exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
See EXAMPLES of 12.9.23
12.9.28

table().col().assign double()

NAME
table().col().assign double() — Assign value to the cell directly as real number (double type)234

SFITSIO User’s Reference GuideSYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_double( double value,long row_index );fits_table_col &table( ... ).col( ... ).assign_double( double value,long row_index, const char *elem_name, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign_double( double value,long row_index, long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign double() assigns value to the cell directly as real number (doubletype). This function can access the value fastest when the column type is FITS::DOUBLE_T(includes ’D’ in TFORMn). However, these functions does not convert the value by TZEROn
and TSCALn of header.
If the column type is integer, it stores the rounded value.
When the column type is boolean, it rounds the value, and if the value is 0 then stores ’F’,
and ’T’ otherwise.
If the column type is string, it formats with "%.15G" of printf() and stores it.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] value
the value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign double() returns reference to the fits table col object
EXCEPTION
If the API fails to manipulate internal buffer (for exapmle, value formatting failure), it
throws an exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
See EXAMPLES of 12.9.23
12.9.29

table().col().assign bit()

NAME
table().col().assign bit() — Assign value to the cell directly as integer (bit type)SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_bit( long value,long row_index );fits_table_col &table( ... ).col( ... ).assign_bit( long value,Ver. 1.2.1

235

long row_index, const char *elem_name, long repetition_idx = 0, nbit = 0 );fits_table_col &table( ... ).col( ... ).assign_bit( long value,long row_index, long elem_index, long repetition_idx = 0, nbit = 1 );DESCRIPTION
table().col().assign bit() assigns value to the cell directly as integer (bit type). Thisfunction can access the value fastest when the column type is FITS::BIT_T (includes ’X’
in TFORMn).
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
Argument nbit indicates how many bits to the right from specified element. If nbit is zero,
bit-field description specified with TELEMn, which is counted from specified element to theright, is used. See also §10.10 for bit-field description.
Though this function can be used to integer and real number type column, these functions
does not convert with TZEROn and TSCALn of header.
When the column type is boolean, it stores ’F’ if the value is 0, and ’T’ otherwise.
If the column type is string, it stores the "%ld" formatted string of printf().
The index begins with zero.
PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign bit() returns reference to the fits table col object
EXCEPTION
If the API fails to manipulate internal buffer (for example, value formatting failure), it
throws an exception derived from SLLIB (sli::err_rec exception).
EXAMPLES
See EXAMPLES of 12.9.23
12.9.30

table().col().assign logical()

NAME
table().col().assign logical() — Assign value to the cell directly as boolean
SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_logical( int value,long row_index );fits_table_col &table( ... ).col( ... ).assign_logical( int value,long row_index, const char *elem_name, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign_logical( int value,long row_index, long elem_index, long repetition_idx = 0 );

236

SFITSIO User’s Reference Guide

DESCRIPTION
table().col().assign logical() assigns the value to the cell directly as boolean. Thisfunction can access the value fastest when the column type is FITS::LOGICAL_T (includes’L’ in TFORMn).
When the column type is boolean, it assigns ’T’ if the value is ’T’ and assigns ’F’ if thevalue is ’F’ and ’\0’ otherwise.
When the column type is integer or real number, it assigns 1 if the value is ’T’, and 0
otherwise. However, it does not convert with TZEROn and TSCALn of header.
When the column type is string, it assigns "T" if the value is ’T’, assigns "F" if the value
is ’F’, and "U" otherwise.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign logical() returns reference to the fits table col object
EXAMPLES
See EXAMPLES of 12.9.23
12.9.31table().col().assign string()

NAME
table().col().assign string() — Assign value to the cell directly as string
SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_string( const char *value,long row_index );fits_table_col &table( ... ).col( ... ).assign_string( const char *value,long row_index, const char *elem_name, long repetition_idx = 0 );fits_table_col &table( ... ).col( ... ).assign_string( const char *value,long row_index, long elem_index, long repetition_idx = 0 );DESCRIPTION
table().col().assign string() assigns a value to the cell directly as a string.
As for a boolean column, when the value can be converted to real number, if the value is
0 then ’F’, otherwise ’T’ is stored. When the value cannot be converted to real number, if
the value begins with ’T’ or ’t’ then ’T’, if it begins with ’F’ or ’f’ then ’F’, otherwise’\0’ is stored.

Ver. 1.2.1

237

If the column type is real number, the value is converted to real number and then stored. If
the column type is integer, the value is converted to real number and then rounded value
is stored. The value is not converted, however, by using a value of TZEROn and TSCALnof a header.
To specify row, use row_index. To specify element, use elem_name or elem_index. For
elem_name, a name which exists in TELEMn can be specified.
If TDIMn is specified, elem_index can be specidied as the first dimensional index, andrepetition_idx can be specified as the second dimensional index.
The index begins with zero.
PARAMETER[I] value
value to assign[I] row_index
row index[I] elem_nameelement name[I] elem_index
element index (the first dimension index of TDIMn)[I] repetiton_index second dimensional index([I] : input, [O] : output)
RETURN VALUE
table().col().assign string() returns reference to the fits table col object.
EXAMPLES
See EXAMPLES of 12.9.23
12.9.32

table().col().assign arrdesc()

NAME
table().col().assign arrdesc() — Assign values of array descriptor to the cell
SYNOPSIS
fits_table_col &table( ... ).col( ... ).assign_arrdesc( long length, long offset,
long row_index,
long elem_index = 0 );DESCRIPTIONThis member function assigns length (length of variable length array) and offset (addressof byte data in the heap area) of variable length arrays to the cell on the main table.
Set elem index to select an array, when a row has multiple variable length arrays.
The index and the address begin with zero.
PARAMETER[I] length
number of array elements[I] offset
0-indexed byte address in the heap area to be referred[I] row_index
row index[I] elem_index index of array to be selected (can be omitted)([I] : input, [O] : output)
RETURN VALUEThis member function returns reference to the fits table col object.
EXAMPLES
See sample/create_vl_array.cc in SFITSIO source package.

238

13

SFITSIO User’s Reference Guide

APPENDIX1: Sample Programs

SFITSIO source package contains sample programs suitable to learn programming with SFITSIO.
We summarize these programs in this section.
• sample/read_and_write.cc
This program simply reads data contents from a FITS file and writes them to another file.
• sample/create_image.cc
This program is shown in §2.4 but creates unsigned 16-bit images.
• sample/create_image_and_header.cc
This program creates a new FITS file having two Image HDUs. The code will helpful tolearn editing FITS header and accessing internal image buffer of fits image objects.
• sample/create_bintable.cc
This program creates a new binary table. The code will helpful to learn handling NULL
value and default values when resizing number of rows.
• sample/create_asciitable.cc
This program creates an ASCII table.
• sample/dump_table.cc
This program displays data contents in an ASCII table or a binary table. Note that variable
length arrays are not supported in this code.
• sample/create_vl_array.cc
This program creates a binary table having a variable length array. The code uses low-level
APIs, therefore, only for advanced users.
• sample_wcs/wcs_test.cc
This program converts pixel coordinates to sky coordinates in specified FITS file. The codeuses APIs of both SFITSIO and libwcs of WCSTools.
• tools/conv_bitpix.cc
A tool to convert BITPIX of image in Primary HDU.
See also the description of image().convert type() member function. (§12.6.13)• tools/create_from_template.c
A tool to create a FITS file from a FITS template written in plain text. To test this program,use template files prepared in tools/template/ directory.
See also §8 “Template Files”.
• tools/fill_header_comments.cc
A tool to complete the comments of header records having blank comments using SFITSIO
built-in comment dictionary (§14)
See also the description of hdu(...).header fill blank comments() member function. (§12.4.38)

Ver. 1.2.1

239• tools/stat_pixels.cc
A tool to compute and print image pixel statistics similar to “imstat” task of IRAF.
See also the description of image(...).stat pixels(...) member function. (§12.6.42)• tools/combine_images.cc
A tool to combine images similar to “imcombine” task of IRAF.
Command arguments look like that of imcombine task, however, the basic implementation is
the same as that often used in IDL script: 1. multiple image data are stored into 3-D array,
2. perform combine.
See also the description of image(...).combine layers(...) member function. (§12.6.42)• tools/hv.cc
This tool rapidly displays all header records. The code uses low-level APIs, therefore, only
for advanced users.
Disk seek is applied for uncompressed FITS file on local disk. In addition, this tool does notread Data Unit when EXTEND is F even for compressed FITS files read via network. That is
why hv.cc works with high-speed.
See also §12.5.1 and and succeeding subsections.
• tools/dataunit_md5.cc
This tool computes MD5 of each Data Unit of a FITS file. The code uses low-level APIs,
therefore, only for advanced users.
Users can use this program to certify an identity of data in Data Unit.

240

SFITSIO User’s Reference Guide

14

APPENDIX2: SFITSIO built-in comment dictionary of FITS
headerSFITSIO built-in comment dictionary is expressed in associative arrays of the following code.
Using some member functions of SFITSIO, appropriate comments are automatically appended for
keywords found in the associative arrays.
/** See http://heasarc.gsfc.nasa.gov/docs/fcg/standard_dict.html for FITS
* standard keywords and comments.
*/
static asarray_tstring Fallback_comments(/* associative array *//*|MIN
MAX| *//* system keywords */"SIMPLE","conformity to FITS standard","BITPIX","number of bits per data pixel","NAXIS","number of data axes","NAXIS#","length of data axis #","EXTEND","possibility of presence of extensions","XTENSION", "type of extension","PCOUNT","number of parameters per group","GCOUNT","number of groups","EXTNAME", "name of this HDU","EXTVER","version of the extension","EXTLEVEL", "hierarchical level of the extension",/*|MIN
MAX| *//* standard of JAXA data center */"FMTTYPE", "type of format in FITS file","FTYPEVER", "version of FMTTYPE definition","FMTVER","version of FMTTYPE definition",/* standard keywords */"DATE","date of file creation","ORIGIN","organization responsible for the data","AUTHOR","author of the data","REFERENC", "bibliographic reference","DATE-OBS", "date of the observation","TELESCOP", "telescope or mission name","INSTRUME", "instrument name","DETECTOR", "detector name","OBSERVER", "observer who acquired the data","OBJECT","name of observed object",/*|MIN
MAX| */"EPOCH","equinox of celestial coordinate system","EQUINOX", "equinox of celestial coordinate system","TIMESYS", "explicit time scale specification",/* other general keywords */"OBSERVAT", "observatory name","CREATOR", "data generator program","PIPELINE", "data processing pipeline name","FILENAME", "file name","PROPOSAL", "proposal ID",
"BAND","band name","MJD","modified Julian date","AIRMASS", "air mass","EXPTIME", "exposure time","WEATHER", "weather condition",

Ver. 1.2.1/* general keyword of JAXA data center */"CNTTYPE", "type of data content","CNTVER","version of data content","CHECKSUM", "HDU checksum","DATASUM", "data unit checksum",
/*
|MIN
NULL

241

MAX| */);
static asarray_tstring Image_comments(/* associative array *//*|MIN
MAX| */"BZERO","zero point in scaling equation","BSCALE","linear factor in scaling equation","BLANK","value used for undefined pixels","BUNIT","physical unit of the pixel values","DATAMIN", "minimum data value","DATAMAX", "maximum data value",/* WCS */"WCSAXES?", "number of axes for WCS","CRVAL#?", "world coordinate at reference point","CRPIX#?", "pixel coordinate at reference point","CDELT#?", "world coordinate increment at reference point","CROTA#","coordinate system rotation angle","CTYPE#?", "type of celestial system and projection system",/*|MIN
MAX| */"CUNIT#?", "units of the coordinates along axis","PC#_#?","matrix of rotation (#,#)","CD#_#?","matrix of rotation and scale (#,#)","WCSNAME?", "name of WCS","LONPOLE?", "native longitude of celestial pole","LATPOLE?", "native latitude of celestial pole","EQUINOX?", "equinox of celestial coordinate system","MJD-OBS", "modified Julian date of observation","CNAME#?", "description of CTYPE definition","RADESYS?", "default coordinate system",/*|MIN
MAX| */
NULL);
static asarray_tstring Binary_table_comments(/* associative array *//*|MIN
MAX| */"BITPIX","number of bits per data element","NAXIS1","width of table in bytes","NAXIS2","number of rows in table","PCOUNT","length of reserved area and heap","TFIELDS", "number of fields in each row","TXFLDKWD", "extended field keywords",/* JAXA ext. */"TTYPE#","field name","TALAS#","aliases of field name",/* JAXA ext. */"TELEM#","element names",/* JAXA ext. */"TUNIT#","physical unit","TDISP#","display format","TFORM#","data format","TDIM#","dimensionality of the array","TZERO#","zero point in scaling equation","TSCAL#","linear factor in scaling equation","TNULL#","value used for undefined cells","THEAP","byte offset to heap area",

242

SFITSIO User’s Reference Guide/* CFITSIO ext. */"TLMIN#","minimum value legally allowed","TLMAX#","maximum value legally allowed","TDMIN#","minimum data value","TDMAX#","maximum data value",
/*
|MIN
NULL

MAX| */);
static asarray_tstring Ascii_table_comments(/* associative array *//*|MIN
MAX| */"BITPIX","number of bits per data element","NAXIS1","width of table in bytes","NAXIS2","number of rows in table","TFIELDS", "number of fields in each row","TXFLDKWD", "extended field keywords",/* JAXA ext. */"TTYPE#","field name","TALAS#","aliases of field name",/* JAXA ext. */"TUNIT#","physical unit","TFORM#","display format","TBCOL#","starting position in bytes","TZERO#","zero point in scaling equation","TSCAL#","linear factor in scaling equation","TNULL#","value used for undefined cells","TLMIN#","minimum value legally allowed","TLMAX#","maximum value legally allowed","TDMIN#","minimum data value","TDMAX#","maximum data value",/*|MIN
MAX| */NULL);

Ver. 1.2.1

15

243

APPENDIX3: How to Use Handy TSTRING Class

The “tstring” class used inside of SFITSIO keeps the usability of C language and can process strings
easily like the script languages.43) If you already imported SFITSIO, you can use it immediately
with writing as follows,¨¥#include <sli/tstring.h>using namespace sli;§¦

Create an Object and Substitute/Display a String¨¥

tstring my_string;
my_string = "I am a SFITSIO user!";§¦With the code above, the creation of an object and the substitution of a string into the object
has done. Users do not need to care the size of buffer at a substitution or an edition of a string,
because the object automatically manages its own buffer for strings internally. In addition, users
do not concern the memory leak since the buffer area automatically frees when the process exitedthe scope.
It is also possible to substitute with using .printf(). In this case, it is also not necessary tocare of the buffer area.
¨¥

my_string.printf("Today is %d/%d/%d", y, m, d);§¨Next, the content of my string will be displayed with printf().
printf("my_string = %s\n", my_string.cstr());

§

¦
¥
¦

Use .cstr() when the address of the string is needed as in case when giving it to the printf()
function.

Edit Strings¨¥

my_string = "I am ";my_string += "a SFITSIO ";my_string.append("user!");§/* Substitution *//* Addition *//* Addition */If you want to add string into the existing string, use “+=” or .append() as the example above.
Insert "super " into the head of "SFITSIO" in the strings above.
¨

my_string.insert(7,"super ");

§

¦

¥
¦

Now it makes "I am a super SFITSIO user!".
Many other member functions are available such as .replace() to replace, .erase() to erase,.chop() and .chomp() having the same functions as those in Perl, .trim() to erase spaces in theends, and .toupper() and .tolower() to transform between upper cases and lower cases.

Search Strings and Use Regular Expression
It is easy for member functions to access each character in the internal string and to search or
replace with a regular expression. As the regular expression, POSIX-extended regular-expressions
are available.
The following code displays each one character in the content of my string.
43)

Although there is another way to use string in C++ standard library, tstring class has lower barrier and issimpler for the C users because this has variety of member functions.

244
¨

§

SFITSIO User’s Reference Guidesize_t i;for ( i=0 ; i < my_string.length() ; i++ ) {printf("ch[%d] = %c\n", i, my_string.cchr(i));}¥¦.length() is used to obtain the length of the strings. It is the same way as in SFITSIO.
It is also possible to read/write each one character with using “[]”. The following example
replaces every space character with an underscore.
¨

§
¨

§

size_t i;for ( i=0 ; i < my_string.length() ; i++ ) {if ( my_string[i] == ’ ’ ) my_string[i] = ’_’;}
Search with using regular expressions.

¥¦¥ssize_t pos;size_t len;pos = my_string.regmatch("[A-Z]+", &len);¦

The position at which the pattern is matched and the length of the string matching the pattern
are given to pos and len, respectively.
Finally, the following code introduces the example of replacing with using a regular expression.
¨§

tstring my_string = "TSTRING isvery
my_string.regreplace("[ ]+", " ", true);easy !";

The code replaces more than one space characters with one space character.

Official Manual
PDF manual is available. For more information, see this link.
http://www.ir.isas.jaxa.jp/~cyamauch/sli/sllib.pdf¥¦

Ver. 1.2.1

16

245

APPENDIX4: Convenient usage of DIGESTSTREAMIO class.read_stream() and .write_stream() in SFITSIO support network and compressed file; this isachieved by digeststreamio class. Using digeststreamio class, user simply have to write a code in thesame manner as that of fgets() in libc to connect to the network and compress/extract compressedstream. As for compression format, it supports gzip and bzip2. If SFITSIO is installed, write as
follow to use digeststreamio class.
¨¥#include <sli/digeststreamio.h>using namespace sli;§¦

Open and Close of File¨§

int status;
digeststreamio dsio;
status = dsio.open("r", "http://www.jaxa.jp/");¥¦To open file, use .open(). Give "r" (read) or "w" (write) to the first argument and path to thesecond argument. http://..., ftp://... or file://... can be given for the path. file:// canbe omitted. open() returns negative value in case of error.
To close file, use .close().
¨§¥

dsio.close();¦Readgetstr() and getchr() correspond to fgets() and fgetc() in libc, respectively. For member function
name of digeststreamio, chr is used when it is character and str is used when it is string. Usethem as follows.
¨

§
¨

§

¥

char buf[256];
while ( dsio.getstr(buf, 256) != NULL ) {printf("%s", buf);}
int ch;while ( (ch = dsio.getchr()) != EOF ) {printf("%c", ch);}.getline() enables reading line by line including break in each line.
¨§

const char *ptr;
while ( (ptr = dsio.getline()) != NULL ) {printf("%s", ptr);
}

¦
¥

¦
¥

¦

Write
To write a string, use .putstr().
¨§dsio.putstr(buf);.printf() also can be used.
¨§dsio.printf("Today is %d/%d/%d\n", y, m, d);

¥
¦
¥
¦

246

SFITSIO User’s Reference Guide

STDSTREAMIO class
SLLIB which provides tstring class and digeststreamio class and so on provides most functionsof libc. Using the class in SLLIB to write routine functions such as printf() enables to write
object-oriented and unified code.
For example, printf() and putchar() in libc can be replaced by member function of stdstreamio
class. The following code sample displays HTML of http://www.jaxa.jp/.
¨¥#include <sli/digestststreamio.h>#include <sli/stdststreamio.h>#include <sli/tstring.h>using namespace sli;
int main(){tstring buf;
digeststreamio dsin;
stdstreamio sio;
dsin.openf("r", "%s:/%s", "http", "/www.jaxa.jp/");while ( (buf = dsin.getline()) != NULL ) {sio.printf("%s", buf);}
dsin.close();return 0;}§¦

Using .openf(), the path can be given in a variable length argument as well as printf(). Like this,a lot of member functions whose name suffix is “f” are available in classes in SLLIB. Since thevariable length argument can be used for their member functions, code can be written briefly.
Because parent class of stdstreamio class is the same as that of digeststreamio class, the same
member functions as that of digeststreamio class are available.

Official Manual
PDF manual is available. For more information, see this link.
http://www.ir.isas.jaxa.jp/~cyamauch/sli/sllib.pdf