1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-2004, 2006 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 #include <language/data-io/data-writer.h>
28 #include <data/file-name.h>
29 #include <language/data-io/file-handle.h>
30 #include <libpspp/alloc.h>
31 #include <libpspp/assertion.h>
32 #include <libpspp/message.h>
33 #include <libpspp/str.h>
38 #define _(msgid) gettext (msgid)
40 /* Data file writer. */
43 struct file_handle *fh; /* File handle. */
44 FILE *file; /* Associated file. */
47 /* Opens a file handle for writing as a data file. */
49 dfm_open_writer (struct file_handle *fh)
54 aux = fh_open (fh, FH_REF_FILE, "data file", "ws");
60 w = *aux = xmalloc (sizeof *w);
62 w->file = fn_open (fh_get_file_name (w->fh), "wb");
66 msg (ME, _("An error occurred while opening \"%s\" for writing "
67 "as a data file: %s."),
68 fh_get_file_name (w->fh), strerror (errno));
79 /* Returns false if an I/O error occurred on WRITER, true otherwise. */
81 dfm_write_error (const struct dfm_writer *writer)
83 return ferror (writer->file);
86 /* Writes record REC (which need not be null-terminated) having
87 length LEN to the file corresponding to HANDLE. Adds any
88 needed formatting, such as a trailing new-line. Returns true
89 on success, false on failure. */
91 dfm_put_record (struct dfm_writer *w, const char *rec, size_t len)
95 if (dfm_write_error (w))
98 switch (fh_get_mode (w->fh))
101 fwrite (rec, len, 1, w->file);
102 putc ('\n', w->file);
107 size_t record_width = fh_get_record_width (w->fh);
108 size_t write_bytes = MIN (len, record_width);
109 size_t pad_bytes = record_width - write_bytes;
110 fwrite (rec, write_bytes, 1, w->file);
111 while (pad_bytes > 0)
113 static const char spaces[32] = " ";
114 size_t chunk = MIN (pad_bytes, sizeof spaces);
115 fwrite (spaces, chunk, 1, w->file);
125 return !dfm_write_error (w);
128 /* Closes data file writer W. */
130 dfm_close_writer (struct dfm_writer *w)
137 file_name = xstrdup (fh_get_name (w->fh));
138 if (fh_close (w->fh, "data file", "ws"))
147 ok = !dfm_write_error (w) && !fn_close (file_name, w->file);
150 msg (ME, _("I/O error occurred writing data file \"%s\"."), file_name);