-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreader.c
More file actions
99 lines (84 loc) · 2.38 KB
/
reader.c
File metadata and controls
99 lines (84 loc) · 2.38 KB
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
/*
* reader.c
*/
#include "error.h"
#include "reader.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* The file being read. */
FILE* reader_file;
/* The name of the file being currently read, without extension. */
char* reader_file_name_base;
/**
* Open a file for reading.
* Store the file pointer in the reader's global variable.
*/
void reader_open_file(const char* file_name) {
char* full_file_name;
/* Create a string with the file name and extension. */
/* Store the file name for error reporting and for creating output files. */
reader_file_name_base = (char*)malloc(strlen(file_name) + 1);
if (!reader_file_name_base)
error_fatal(ErrorMemoryAlloc);
strcpy(reader_file_name_base, file_name);
full_file_name = reader_get_file_name(ReaderFileExtension);
/* Open the file. */
reader_file = fopen(full_file_name, "r");
if (!reader_file) {
fprintf(stderr, ErrorCantRead, full_file_name);
fprintf(stderr, "\n");
free(full_file_name);
exit(EXIT_FAILURE);
}
free(full_file_name);
}
char* reader_get_file_name(const char* extension) {
char* file_name;
unsigned int full_length, base_length = strlen(reader_file_name_base);
full_length = base_length + strlen(extension) + 1;
file_name = (char*)malloc(full_length);
if (!file_name)
error_fatal(ErrorMemoryAlloc);
strcpy(file_name, reader_file_name_base);
/* Add the file extension. */
file_name[base_length] = '.';
strcpy(file_name + base_length + 1, extension);
file_name[full_length] = '\0';
return file_name;
}
/**
* Read the next line from a file.
* The returned string must be freed by the invoker.
*/
char* reader_get_line() {
int length = ReaderLineLengthInit;
int position = 0;
char *line = (char*)malloc(length);
if (!line)
error_fatal(ErrorMemoryAlloc);
do {
line[position++] = getc(reader_file);
/* If the position is divisible by the initial size, then more space is
* needed for the line. */
if(!(position % ReaderLineLengthInit)) {
/* Increase the line length by the initial size. */
length += ReaderLineLengthInit;
line = (char*)realloc(line, length);
if (!line)
error_fatal(ErrorMemoryAlloc);
}
} while (line[position - 1] != '\n' && line[position - 1] != EOF);
if (line[0] == EOF) {
free(line);
return NULL;
}
line[position - 1] = '\0';
return line;
}
/**
* Close the reader's file.
*/
void reader_close_file() {
fclose(reader_file);
}