1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "read_file_names.h"
#define FILE_NAME_ALLOC_SIZE 10
#define FILE_PATH_MAX 2046
/* ----------------------------- MNI Header -----------------------------------
@NAME : read_file_names
@INPUT : filelist - name of file from which to read names
@OUTPUT : num_files - number of files read in
@RETURNS : Pointer to a NULL-terminated array of file names
@DESCRIPTION: Reads in a list of file names from file filelist or stdin if
"-" is specified. Returns NULL if an error occurs. If
no error occurs, then a pointer to an empty array is
returned and num_files is zero.
@METHOD :
@GLOBALS :
@CALLS :
@CREATED : March 8, 1995 (Peter Neelin)
@MODIFIED :
---------------------------------------------------------------------------- */
char **read_file_names(char *filelist, int *num_files)
{
char **files;
int array_size;
int nfiles;
FILE *fp;
char line[FILE_PATH_MAX+1];
int length;
/* Open the file */
if (strcmp(filelist, "-") == 0) {
fp = stdin;
}
else {
fp = fopen(filelist, "r");
if (fp == NULL) {
(void) fprintf(stderr, "Error opening file \"%s\"\n", filelist);
return NULL;
}
}
/* Allocate an initial array and NULL-terminate it */
array_size = FILE_NAME_ALLOC_SIZE;
files = malloc(sizeof(*files) * array_size);
if (files == NULL) {
(void) fprintf(stderr, "Error allocating memory\n");
return NULL;
}
nfiles = 0;
files[nfiles] = NULL;
/* Read in file names */
while (fgets(line, sizeof(line)/sizeof(line[0]), fp) != NULL) {
/* Remove a trailing newline and check that there is a name */
length = strlen(line);
if ((length > 0) && (line[length-1] == '\n')) {
line[length-1] = '\0';
length--;
}
if (length == 0) continue;
/* Make room for names if needed */
while (nfiles >= array_size-1) {
array_size += FILE_NAME_ALLOC_SIZE;
files = realloc(files, sizeof(*files) * array_size);
if (files == NULL) {
(void) fprintf(stderr, "Error allocating memory\n");
return NULL;
}
}
/* Save the name, making sure that the list is NULL-terminated */
files[nfiles] = strdup(line);
if (files[nfiles] == NULL) {
(void) fprintf(stderr, "Error allocating memory\n");
return NULL;
}
nfiles++;
files[nfiles] = NULL;
}
/* Close the file */
(void) fclose(fp);
/* Return the number of files */
*num_files = nfiles;
return files;
}
|