pivot-output: Fix crash when layers axis has no leaves.
[pspp.git] / tests / libpspp / encoding-guesser-test.c
blob36c361ee1af792aadc76344d12e1272dbb6cdca2
1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2011 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/>. */
17 #include <config.h>
19 #include "libpspp/encoding-guesser.h"
21 #include <ctype.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
26 #include "libpspp/i18n.h"
28 #include "gl/error.h"
29 #include "gl/progname.h"
30 #include "gl/xalloc.h"
32 static void
33 usage (void)
35 printf ("usage: %s [OTHER_ENCODING] [BUFSIZE] < INPUT\n"
36 "where OTHER_ENCODING is the fallback encoding (default taken\n"
37 " from the current locale)\n"
38 " and BUFSIZE is the buffer size (default %d)\n",
39 program_name, ENCODING_GUESS_MIN);
40 exit (0);
43 int
44 main (int argc, char *argv[])
46 const char *encoding, *guess;
47 char *buffer;
48 int bufsize;
49 size_t n;
50 int i;
52 set_program_name (argv[0]);
54 i18n_init ();
56 encoding = NULL;
57 bufsize = 0;
58 for (i = 1; i < argc; i++)
60 const char *arg = argv[i];
61 if (!strcmp (arg, "--help"))
62 usage ();
63 else if (isdigit (arg[0]) && bufsize == 0)
65 bufsize = atoi (arg);
66 if (bufsize < ENCODING_GUESS_MIN)
67 error (1, 0, "buffer size %s is less than minimum size %d",
68 arg, ENCODING_GUESS_MIN);
70 else if (!isdigit (arg[0]) && encoding == NULL)
71 encoding = arg;
72 else
73 error (1, 0, "bad syntax; use `%s --help' for help", program_name);
76 if (bufsize == 0)
77 bufsize = ENCODING_GUESS_MIN;
79 buffer = xmalloc (bufsize);
81 n = fread (buffer, 1, bufsize, stdin);
82 guess = encoding_guess_head_encoding (encoding, buffer, n);
83 if (!strcmp (guess, "ASCII") && encoding_guess_encoding_is_auto (encoding))
84 while (n > 0)
86 size_t n_ascii = encoding_guess_count_ascii (buffer, n);
87 if (n == n_ascii)
88 n = fread (buffer, 1, bufsize, stdin);
89 else
91 memmove (buffer, buffer + n_ascii, n - n_ascii);
92 n -= n_ascii;
93 n += fread (buffer + n, 1, bufsize - n, stdin);
95 guess = encoding_guess_tail_encoding (encoding, buffer, n);
96 break;
99 puts (guess);
100 free (buffer);
102 return 0;