1 /* Reading file lists.
2    Copyright (C) 1995-1998, 2000-2002 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 2, or (at your option)
7    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, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
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 "exit.h"
33 #include "getline.h"
34 #include "gettext.h"
35 
36 /* A convenience macro.  I don't like writing gettext() every time.  */
37 #define _(str) gettext (str)
38 
39 
40 /* Read list of filenames from a file.  */
41 string_list_ty *
read_names_from_file(const char * file_name)42 read_names_from_file (const char *file_name)
43 {
44   size_t line_len = 0;
45   char *line_buf = NULL;
46   FILE *fp;
47   string_list_ty *result;
48 
49   if (strcmp (file_name, "-") == 0)
50     fp = stdin;
51   else
52     {
53       fp = fopen (file_name, "r");
54       if (fp == NULL)
55 	error (EXIT_FAILURE, errno,
56 	       _("error while opening \"%s\" for reading"), file_name);
57     }
58 
59   result = string_list_alloc ();
60 
61   while (!feof (fp))
62     {
63       /* Read next line from file.  */
64       int len = getline (&line_buf, &line_len, fp);
65 
66       /* In case of an error leave loop.  */
67       if (len < 0)
68 	break;
69 
70       /* Remove trailing '\n' and trailing whitespace.  */
71       if (len > 0 && line_buf[len - 1] == '\n')
72 	line_buf[--len] = '\0';
73       while (len > 0
74 	     && (line_buf[len - 1] == ' '
75 		 || line_buf[len - 1] == '\t'
76 		 || line_buf[len - 1] == '\r'))
77 	line_buf[--len] = '\0';
78 
79       /* Test if we have to ignore the line.  */
80       if (*line_buf == '\0' || *line_buf == '#')
81 	continue;
82 
83       string_list_append_unique (result, line_buf);
84     }
85 
86   /* Free buffer allocated through getline.  */
87   if (line_buf != NULL)
88     free (line_buf);
89 
90   /* Close input stream.  */
91   if (fp != stdin)
92     fclose (fp);
93 
94   return result;
95 }
96