1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-2004, 2006 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include <language/data-io/data-writer.h>
25 #include <data/file-name.h>
26 #include <language/data-io/file-handle.h>
27 #include <libpspp/alloc.h>
28 #include <libpspp/assertion.h>
29 #include <libpspp/message.h>
30 #include <libpspp/str.h>
35 #define _(msgid) gettext (msgid)
37 /* Data file writer. */
40 struct file_handle *fh; /* File handle. */
41 FILE *file; /* Associated file. */
44 /* Opens a file handle for writing as a data file. */
46 dfm_open_writer (struct file_handle *fh)
51 aux = fh_open (fh, FH_REF_FILE, "data file", "ws");
57 w = *aux = xmalloc (sizeof *w);
59 w->file = fn_open (fh_get_file_name (w->fh), "wb");
63 msg (ME, _("An error occurred while opening \"%s\" for writing "
64 "as a data file: %s."),
65 fh_get_file_name (w->fh), strerror (errno));
76 /* Returns false if an I/O error occurred on WRITER, true otherwise. */
78 dfm_write_error (const struct dfm_writer *writer)
80 return ferror (writer->file);
83 /* Writes record REC (which need not be null-terminated) having
84 length LEN to the file corresponding to HANDLE. Adds any
85 needed formatting, such as a trailing new-line. Returns true
86 on success, false on failure. */
88 dfm_put_record (struct dfm_writer *w, const char *rec, size_t len)
92 if (dfm_write_error (w))
95 switch (fh_get_mode (w->fh))
98 fwrite (rec, len, 1, w->file);
104 size_t record_width = fh_get_record_width (w->fh);
105 size_t write_bytes = MIN (len, record_width);
106 size_t pad_bytes = record_width - write_bytes;
107 fwrite (rec, write_bytes, 1, w->file);
108 while (pad_bytes > 0)
110 static const char spaces[32] = " ";
111 size_t chunk = MIN (pad_bytes, sizeof spaces);
112 fwrite (spaces, chunk, 1, w->file);
122 return !dfm_write_error (w);
125 /* Closes data file writer W. */
127 dfm_close_writer (struct dfm_writer *w)
134 file_name = xstrdup (fh_get_name (w->fh));
135 if (fh_close (w->fh, "data file", "ws"))
144 ok = !dfm_write_error (w) && !fn_close (file_name, w->file);
147 msg (ME, _("I/O error occurred writing data file \"%s\"."), file_name);