Imported Upstream version 0.19.7
[platform/upstream/gettext.git] / gettext-tools / src / file-list.c
1 /* Reading file lists.
2    Copyright (C) 1995-1998, 2000-2002, 2007, 2015 Free Software
3    Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
21
22 /* Specification.  */
23 #include "file-list.h"
24
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include "str-list.h"
31 #include "error.h"
32 #include "gettext.h"
33
34 /* A convenience macro.  I don't like writing gettext() every time.  */
35 #define _(str) gettext (str)
36
37
38 /* Read list of filenames from a file.  */
39 string_list_ty *
40 read_names_from_file (const char *file_name)
41 {
42   size_t line_len = 0;
43   char *line_buf = NULL;
44   FILE *fp;
45   string_list_ty *result;
46
47   if (strcmp (file_name, "-") == 0)
48     fp = stdin;
49   else
50     {
51       fp = fopen (file_name, "r");
52       if (fp == NULL)
53         error (EXIT_FAILURE, errno,
54                _("error while opening \"%s\" for reading"), file_name);
55     }
56
57   result = string_list_alloc ();
58
59   while (!feof (fp))
60     {
61       /* Read next line from file.  */
62       int len = getline (&line_buf, &line_len, fp);
63
64       /* In case of an error leave loop.  */
65       if (len < 0)
66         break;
67
68       /* Remove trailing '\n' and trailing whitespace.  */
69       if (len > 0 && line_buf[len - 1] == '\n')
70         line_buf[--len] = '\0';
71       while (len > 0
72              && (line_buf[len - 1] == ' '
73                  || line_buf[len - 1] == '\t'
74                  || line_buf[len - 1] == '\r'))
75         line_buf[--len] = '\0';
76
77       /* Test if we have to ignore the line.  */
78       if (*line_buf == '\0' || *line_buf == '#')
79         continue;
80
81       string_list_append_unique (result, line_buf);
82     }
83
84   /* Free buffer allocated through getline.  */
85   if (line_buf != NULL)
86     free (line_buf);
87
88   /* Close input stream.  */
89   if (fp != stdin)
90     fclose (fp);
91
92   return result;
93 }