1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-2004, 2006 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 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, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 #include <language/data-io/data-writer.h>
27 #include <data/file-name.h>
28 #include <language/data-io/file-handle.h>
29 #include <libpspp/alloc.h>
30 #include <libpspp/assertion.h>
31 #include <libpspp/message.h>
32 #include <libpspp/str.h>
37 #define _(msgid) gettext (msgid)
39 /* Data file writer. */
42 struct file_handle *fh; /* File handle. */
43 FILE *file; /* Associated file. */
46 /* Opens a file handle for writing as a data file. */
48 dfm_open_writer (struct file_handle *fh)
53 aux = fh_open (fh, FH_REF_FILE, "data file", "ws");
59 w = *aux = xmalloc (sizeof *w);
61 w->file = fn_open (fh_get_file_name (w->fh), "wb");
65 msg (ME, _("An error occurred while opening \"%s\" for writing "
66 "as a data file: %s."),
67 fh_get_file_name (w->fh), strerror (errno));
78 /* Returns false if an I/O error occurred on WRITER, true otherwise. */
80 dfm_write_error (const struct dfm_writer *writer)
82 return ferror (writer->file);
85 /* Writes record REC (which need not be null-terminated) having
86 length LEN to the file corresponding to HANDLE. Adds any
87 needed formatting, such as a trailing new-line. Returns true
88 on success, false on failure. */
90 dfm_put_record (struct dfm_writer *w, const char *rec, size_t len)
94 if (dfm_write_error (w))
97 switch (fh_get_mode (w->fh))
100 fwrite (rec, len, 1, w->file);
101 putc ('\n', w->file);
106 size_t record_width = fh_get_record_width (w->fh);
107 size_t write_bytes = MIN (len, record_width);
108 size_t pad_bytes = record_width - write_bytes;
109 fwrite (rec, write_bytes, 1, w->file);
110 while (pad_bytes > 0)
112 static const char spaces[32] = " ";
113 size_t chunk = MIN (pad_bytes, sizeof spaces);
114 fwrite (spaces, chunk, 1, w->file);
124 return !dfm_write_error (w);
127 /* Closes data file writer W. */
129 dfm_close_writer (struct dfm_writer *w)
136 file_name = xstrdup (fh_get_name (w->fh));
137 if (fh_close (w->fh, "data file", "ws"))
146 ok = !dfm_write_error (w) && !fn_close (file_name, w->file);
149 msg (ME, _("I/O error occurred writing data file \"%s\"."), file_name);