Use new Gnulib function dtoastr() to format short, accurate real numbers.
[pspp-builds.git] / src / data / csv-file-writer.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2010, 2011 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18
19 #include "data/csv-file-writer.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <math.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <sys/stat.h>
27 #include <time.h>
28
29 #include "data/calendar.h"
30 #include "data/case.h"
31 #include "data/casewriter-provider.h"
32 #include "data/casewriter.h"
33 #include "data/data-out.h"
34 #include "data/dictionary.h"
35 #include "data/file-handle-def.h"
36 #include "data/file-name.h"
37 #include "data/format.h"
38 #include "data/make-file.h"
39 #include "data/missing-values.h"
40 #include "data/settings.h"
41 #include "data/value-labels.h"
42 #include "data/variable.h"
43 #include "libpspp/assertion.h"
44 #include "libpspp/i18n.h"
45 #include "libpspp/message.h"
46 #include "libpspp/str.h"
47
48 #include "gl/ftoastr.h"
49 #include "gl/minmax.h"
50 #include "gl/unlocked-io.h"
51 #include "gl/xalloc.h"
52
53 #include "gettext.h"
54 #define _(msgid) gettext (msgid)
55 #define N_(msgid) (msgid)
56
57 /* A variable in a CSV file. */
58 struct csv_var
59   {
60     int width;                     /* Variable width (0 to 32767). */
61     int case_index;                /* Index into case. */
62     struct fmt_spec format;        /* Print format. */
63     struct missing_values missing; /* User-missing values, if recoding. */
64     struct val_labs *val_labs;  /* Value labels, if any and they are in use. */
65   };
66
67 /* Comma-separated value (CSV) file writer. */
68 struct csv_writer
69   {
70     struct file_handle *fh;     /* File handle. */
71     struct fh_lock *lock;       /* Mutual exclusion for file. */
72     FILE *file;                 /* File stream. */
73     struct replace_file *rf;    /* Ticket for replacing output file. */
74
75     struct csv_writer_options opts;
76
77     char *encoding;             /* Encoding used by variables. */
78
79     /* Variables. */
80     struct csv_var *csv_vars;   /* Variables. */
81     size_t n_csv_vars;         /* Number of variables. */
82   };
83
84 static const struct casewriter_class csv_file_casewriter_class;
85
86 static void write_var_names (struct csv_writer *, const struct dictionary *);
87
88 static bool write_error (const struct csv_writer *);
89 static bool close_writer (struct csv_writer *);
90
91 /* Initializes OPTS with default options for writing a CSV file. */
92 void
93 csv_writer_options_init (struct csv_writer_options *opts)
94 {
95   opts->recode_user_missing = false;
96   opts->include_var_names = false;
97   opts->use_value_labels = false;
98   opts->use_print_formats = false;
99   opts->decimal = settings_get_decimal_char (FMT_F);
100   opts->delimiter = 0;
101   opts->qualifier = '"';
102 }
103
104 /* Opens the CSV file designated by file handle FH for writing cases from
105    dictionary DICT according to the given OPTS.
106
107    No reference to D is retained, so it may be modified or
108    destroyed at will after this function returns. */
109 struct casewriter *
110 csv_writer_open (struct file_handle *fh, const struct dictionary *dict,
111                  const struct csv_writer_options *opts)
112 {
113   struct csv_writer *w;
114   int i;
115
116   /* Create and initialize writer. */
117   w = xmalloc (sizeof *w);
118   w->fh = fh_ref (fh);
119   w->lock = NULL;
120   w->file = NULL;
121   w->rf = NULL;
122
123   w->opts = *opts;
124
125   w->encoding = (dict_get_encoding (dict)
126                  ? xstrdup (dict_get_encoding (dict))
127                  : NULL);
128
129   w->n_csv_vars = dict_get_var_cnt (dict);
130   w->csv_vars = xnmalloc (w->n_csv_vars, sizeof *w->csv_vars);
131   for (i = 0; i < w->n_csv_vars; i++)
132     {
133       const struct variable *var = dict_get_var (dict, i);
134       struct csv_var *cv = &w->csv_vars[i];
135
136       cv->width = var_get_width (var);
137       cv->case_index = var_get_case_index (var);
138
139       cv->format = *var_get_print_format (var);
140       if (opts->recode_user_missing)
141         mv_copy (&cv->missing, var_get_missing_values (var));
142       else
143         mv_init (&cv->missing, cv->width);
144
145       if (opts->use_value_labels)
146         cv->val_labs = val_labs_clone (var_get_value_labels (var));
147       else
148         cv->val_labs = NULL;
149     }
150
151   /* Open file handle as an exclusive writer. */
152   /* TRANSLATORS: this fragment will be interpolated into messages in fh_lock()
153      that identify types of files. */
154   w->lock = fh_lock (fh, FH_REF_FILE, N_("CSV file"), FH_ACC_WRITE, true);
155   if (w->lock == NULL)
156     goto error;
157
158   /* Create the file on disk. */
159   w->rf = replace_file_start (fh_get_file_name (fh), "w", 0666,
160                               &w->file, NULL);
161   if (w->rf == NULL)
162     {
163       msg (ME, _("Error opening `%s' for writing as a system file: %s."),
164            fh_get_file_name (fh), strerror (errno));
165       goto error;
166     }
167
168   if (opts->include_var_names)
169     write_var_names (w, dict);
170
171   if (write_error (w))
172     goto error;
173
174   return casewriter_create (dict_get_proto (dict),
175                             &csv_file_casewriter_class, w);
176
177 error:
178   close_writer (w);
179   return NULL;
180 }
181
182 static bool
183 csv_field_needs_quoting (struct csv_writer *w, const char *s, size_t len)
184 {
185   const char *p;
186
187   for (p = s; p < &s[len]; p++)
188     if (*p == w->opts.qualifier || *p == w->opts.delimiter
189         || *p == '\n' || *p == '\r')
190       return true;
191
192   return false;
193 }
194
195 static void
196 csv_output_buffer (struct csv_writer *w, const char *s, size_t len)
197 {
198   if (csv_field_needs_quoting (w, s, len))
199     {
200       const char *p;
201
202       putc (w->opts.qualifier, w->file);
203       for (p = s; p < &s[len]; p++)
204         {
205           if (*p == w->opts.qualifier)
206             putc (w->opts.qualifier, w->file);
207           putc (*p, w->file);
208         }
209       putc (w->opts.qualifier, w->file);
210     }
211   else
212     fwrite (s, 1, len, w->file);
213 }
214
215 static void
216 csv_output_string (struct csv_writer *w, const char *s)
217 {
218   csv_output_buffer (w, s, strlen (s));
219 }
220
221 static void
222 write_var_names (struct csv_writer *w, const struct dictionary *d)
223 {
224   size_t i;
225
226   for (i = 0; i < w->n_csv_vars; i++)
227     {
228       if (i > 0)
229         putc (w->opts.delimiter, w->file);
230       csv_output_string (w, var_get_name (dict_get_var (d, i)));
231     }
232   putc ('\n', w->file);
233 }
234
235 static void
236 csv_output_format (struct csv_writer *w, const struct csv_var *cv,
237                    const union value *value)
238 {
239   char *s = data_out (value, w->encoding, &cv->format);
240   struct substring ss = ss_cstr (s);
241   if (cv->format.type != FMT_A)
242     ss_trim (&ss, ss_cstr (" "));
243   else
244     ss_rtrim (&ss, ss_cstr (" "));
245   csv_output_buffer (w, ss.string, ss.length);
246   free (s);
247 }
248
249 static double
250 extract_date (double number, int *y, int *m, int *d)
251 {
252   int yd;
253
254   calendar_offset_to_gregorian (number / 60. / 60. / 24., y, m, d, &yd);
255   return fmod (number, 60. * 60. * 24.);
256 }
257
258 static void
259 extract_time (double number, double *H, int *M, int *S)
260 {
261   *H = floor (number / 60. / 60.);
262   number = fmod (number, 60. * 60.);
263
264   *M = floor (number / 60.);
265   number = fmod (number, 60.);
266
267   *S = floor (number);
268 }
269
270 static void
271 csv_write_var__ (struct csv_writer *w, const struct csv_var *cv,
272                  const union value *value)
273 {
274   const char *label;
275
276   label = val_labs_find (cv->val_labs, value);
277   if (label != NULL)
278     csv_output_string (w, label);
279   else if (cv->width == 0 && value->f == SYSMIS)
280     csv_output_buffer (w, " ", 1);
281   else if (w->opts.use_print_formats)
282     csv_output_format (w, cv, value);
283   else
284     {
285       char s[MAX (DBL_STRLEN_BOUND, 128)];
286
287       switch (cv->format.type)
288         {
289         case FMT_F:
290         case FMT_COMMA:
291         case FMT_DOT:
292         case FMT_DOLLAR:
293         case FMT_PCT:
294         case FMT_E:
295         case FMT_CCA:
296         case FMT_CCB:
297         case FMT_CCC:
298         case FMT_CCD:
299         case FMT_CCE:
300         case FMT_N:
301         case FMT_Z:
302         case FMT_P:
303         case FMT_PK:
304         case FMT_IB:
305         case FMT_PIB:
306         case FMT_PIBHEX:
307         case FMT_RB:
308         case FMT_RBHEX:
309         case FMT_WKDAY:
310         case FMT_MONTH:
311           dtoastr (s, sizeof s, 0, 0, value->f);
312           if (w->opts.decimal != '.')
313             {
314               char *cp = strchr (s, '.');
315               if (cp != NULL)
316                 *cp = w->opts.decimal;
317             }
318           break;
319
320         case FMT_DATE:
321         case FMT_ADATE:
322         case FMT_EDATE:
323         case FMT_JDATE:
324         case FMT_SDATE:
325         case FMT_QYR:
326         case FMT_MOYR:
327         case FMT_WKYR:
328           if (value->f < 0)
329             strcpy (s, " ");
330           else
331             {
332               int y, m, d;
333
334               extract_date (value->f, &y, &m, &d);
335               snprintf (s, sizeof s, "%02d/%02d/%04d", m, d, y);
336             }
337           break;
338
339         case FMT_DATETIME:
340           if (value->f < 0)
341             strcpy (s, " ");
342           else
343             {
344               int y, m, d, M, S;
345               double H;
346
347               extract_time (extract_date (value->f, &y, &m, &d), &H, &M, &S);
348               snprintf (s, sizeof s, "%02d/%02d/%04d %02.0f:%02d:%02d",
349                         m, d, y, H, M, S);
350             }
351           break;
352
353         case FMT_TIME:
354         case FMT_DTIME:
355           {
356             double H;
357             int M, S;
358
359             extract_time (fabs (value->f), &H, &M, &S);
360             snprintf (s, sizeof s, "%s%02.0f:%02d:%02d",
361                       value->f < 0 ? "-" : "", H, M, S);
362           }
363           break;
364
365         case FMT_A:
366         case FMT_AHEX:
367           csv_output_format (w, cv, value);
368           return;
369
370         case FMT_NUMBER_OF_FORMATS:
371           NOT_REACHED ();
372         }
373       csv_output_string (w, s);
374     }
375 }
376
377 static void
378 csv_write_var (struct csv_writer *w, const struct csv_var *cv,
379                const union value *value)
380 {
381   if (mv_is_value_missing (&cv->missing, value, MV_USER))
382     {
383       union value missing;
384
385       value_init (&missing, cv->width);
386       value_set_missing (&missing, cv->width);
387       csv_write_var__ (w, cv, &missing);
388       value_destroy (&missing, cv->width);
389     }
390   else
391     csv_write_var__ (w, cv, value);
392 }
393
394 static void
395 csv_write_case (struct csv_writer *w, const struct ccase *c)
396 {
397   size_t i;
398
399   for (i = 0; i < w->n_csv_vars; i++)
400     {
401       const struct csv_var *cv = &w->csv_vars[i];
402
403       if (i > 0)
404         putc (w->opts.delimiter, w->file);
405       csv_write_var (w, cv, case_data_idx (c, cv->case_index));
406     }
407   putc ('\n', w->file);
408 }
409 \f
410 /* Writes case C to CSV file W. */
411 static void
412 csv_file_casewriter_write (struct casewriter *writer, void *w_,
413                            struct ccase *c)
414 {
415   struct csv_writer *w = w_;
416
417   if (ferror (w->file))
418     {
419       casewriter_force_error (writer);
420       case_unref (c);
421       return;
422     }
423
424   csv_write_case (w, c);
425   case_unref (c);
426 }
427
428 /* Destroys CSV file writer W. */
429 static void
430 csv_file_casewriter_destroy (struct casewriter *writer, void *w_)
431 {
432   struct csv_writer *w = w_;
433   if (!close_writer (w))
434     casewriter_force_error (writer);
435 }
436
437 /* Returns true if an I/O error has occurred on WRITER, false otherwise. */
438 bool
439 write_error (const struct csv_writer *writer)
440 {
441   return ferror (writer->file);
442 }
443
444 /* Closes a CSV file after we're done with it.
445    Returns true if successful, false if an I/O error occurred. */
446 bool
447 close_writer (struct csv_writer *w)
448 {
449   size_t i;
450   bool ok;
451
452   if (w == NULL)
453     return true;
454
455   ok = true;
456   if (w->file != NULL)
457     {
458       if (write_error (w))
459         ok = false;
460       if (fclose (w->file) == EOF)
461         ok = false;
462
463       if (!ok)
464         msg (ME, _("An I/O error occurred writing CSV file `%s'."),
465              fh_get_file_name (w->fh));
466
467       if (ok ? !replace_file_commit (w->rf) : !replace_file_abort (w->rf))
468         ok = false;
469     }
470
471   fh_unlock (w->lock);
472   fh_unref (w->fh);
473
474   free (w->encoding);
475
476   for (i = 0; i < w->n_csv_vars; i++)
477     {
478       struct csv_var *cv = &w->csv_vars[i];
479       mv_destroy (&cv->missing);
480       val_labs_destroy (cv->val_labs);
481     }
482
483   free (w->csv_vars);
484   free (w);
485
486   return ok;
487 }
488
489 /* CSV file writer casewriter class. */
490 static const struct casewriter_class csv_file_casewriter_class =
491   {
492     csv_file_casewriter_write,
493     csv_file_casewriter_destroy,
494     NULL,
495   };