• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Reading file lists.
2    Copyright (C) 1995-1998, 2000-2002, 2007, 2019 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 <https://www.gnu.org/licenses/>.  */
16 
17 #ifdef HAVE_CONFIG_H
18 # include "config.h"
19 #endif
20 
21 /* Specification.  */
22 #include "file-list.h"
23 
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 
29 #include "str-list.h"
30 #include "error.h"
31 #include "gettext.h"
32 
33 /* A convenience macro.  I don't like writing gettext() every time.  */
34 #define _(str) gettext (str)
35 
36 
37 /* Read list of filenames from a file.  */
38 string_list_ty *
read_names_from_file(const char * file_name)39 read_names_from_file (const char *file_name)
40 {
41   size_t line_len = 0;
42   char *line_buf = NULL;
43   FILE *fp;
44   string_list_ty *result;
45 
46   if (strcmp (file_name, "-") == 0)
47     fp = stdin;
48   else
49     {
50       fp = fopen (file_name, "r");
51       if (fp == NULL)
52         error (EXIT_FAILURE, errno,
53                _("error while opening \"%s\" for reading"), file_name);
54     }
55 
56   result = string_list_alloc ();
57 
58   while (!feof (fp))
59     {
60       /* Read next line from file.  */
61       int len = getline (&line_buf, &line_len, fp);
62 
63       /* In case of an error leave loop.  */
64       if (len < 0)
65         break;
66 
67       /* Remove trailing '\n' and trailing whitespace.  */
68       if (len > 0 && line_buf[len - 1] == '\n')
69         line_buf[--len] = '\0';
70       while (len > 0
71              && (line_buf[len - 1] == ' '
72                  || line_buf[len - 1] == '\t'
73                  || line_buf[len - 1] == '\r'))
74         line_buf[--len] = '\0';
75 
76       /* Test if we have to ignore the line.  */
77       if (!(*line_buf == '\0' || *line_buf == '#'))
78         /* Include the line in the result.  */
79         string_list_append_unique (result, line_buf);
80     }
81 
82   /* Free buffer allocated through getline.  */
83   if (line_buf != NULL)
84     free (line_buf);
85 
86   /* Close input stream.  */
87   if (fp != stdin)
88     fclose (fp);
89 
90   return result;
91 }
92