grub2: bring back build of aros-side grub2 tools
[AROS.git] / tools / genmodule / fileread.c
blobe240734b43eb0124e852804758b02bdc907ca218
1 /*
2 Copyright © 1995-2004, The AROS Development Team. All rights reserved.
4 Desc: The functions to read lines from a file
5 */
6 #include <stdio.h>
7 #include <string.h>
8 #include <stdarg.h>
9 #include <stdlib.h>
11 static char *line = NULL; /* The current read file */
12 static char *filename = NULL; /* The name of the opened file */
13 static FILE *file = NULL; /* The opened file */
14 static unsigned int slen = 0; /* The allocation length pointed to be line */
15 static unsigned int lineno = 0; /* The line number, will be increased by one everytime a line is read */
17 int fileopen(const char *fname)
19 if (file!=NULL)
21 fclose(file);
22 free(filename);
23 file = NULL;
24 filename = NULL;
25 lineno = 0;
27 file = fopen(fname, "r");
28 if (file!=NULL)
29 filename = strdup(fname);
31 return file!=NULL;
34 void fileclose(void)
36 if (file!=NULL)
38 fclose(file);
39 free(filename);
40 file = NULL;
41 filename = NULL;
45 char *readline(void)
47 char haseol;
49 if (file==NULL || feof(file))
50 return NULL;
52 if (slen==0)
54 slen = 256;
55 line = malloc(slen);
57 if (fgets(line, slen, file))
59 size_t len = strlen(line);
60 haseol = line[len-1]=='\n';
61 if (haseol) line[len-1]='\0';
63 while (!(haseol || feof(file)))
65 slen += 256;
66 line = (char *)realloc(line, slen);
67 if (fgets(line+len, slen, file))
69 len = strlen(line);
70 haseol = line[len-1]=='\n';
71 if (haseol) line[len-1]='\0';
73 else if (ferror(file))
75 perror(filename);
76 free(line);
77 return NULL;
81 else
82 line[0]='\0';
83 lineno++;
85 return line;
88 void filewarning(const char *format, ...)
90 va_list ap;
92 fprintf(stderr, "%s:%d:warning ", filename, lineno);
94 va_start(ap, format);
95 vfprintf(stderr, format, ap);
96 va_end(ap);
99 void exitfileerror(int code, const char *format, ...)
101 va_list ap;
103 fprintf(stderr, "%s:%d:error ", filename, lineno);
105 va_start(ap, format);
106 vfprintf(stderr, format, ap);
107 va_end(ap);
109 exit(code);