-
Notifications
You must be signed in to change notification settings - Fork 0
/
readfile.c
102 lines (81 loc) · 1.57 KB
/
readfile.c
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
100
101
102
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <conway.h>
#include <readfile.h>
char** init_matrix(char* filename, int* _y, int* _x)
{
char** matrix = NULL;
char* buffer;
size_t y, x;
buffer = read_file(filename);
if (!buffer)
return NULL;
y = strocc(buffer, '\n') + 1;
char* tmp = strchr(buffer, '\n');
if (!tmp)
x = strlen(buffer);
else
x = tmp - buffer;
matrix = matrixdup(NULL, y, x);
if (!matrix)
goto free_buffer;
canonicalize_buffer(buffer);
for (size_t i = 0; i < y; i++) {
for (size_t j = 0; j < x; j++) {
matrix[i][j] = buffer[(x + 1) * i + j];
}
}
*(_y) = y;
if (_x)
*(_x) = x;
free_buffer:
free(buffer);
return matrix;
}
off_t get_file_size(char* filename)
{
struct stat st;
if (stat(filename, &st) == -1)
return -1;
return st.st_size;
}
size_t strocc(const char* str, const char c)
{
size_t counter = 0;
for (size_t i = 0; str[i] != '\0'; i++)
if (str[i] == c)
counter++;
return counter;
}
char* read_file(char* filename)
{
FILE* file;
char* buffer = NULL;
off_t file_size;
file = fopen(filename, "r");
if (!file)
return NULL;
file_size = get_file_size(filename);
if (file_size < 0)
goto close_file;
buffer = calloc(file_size + 1, 1);
if (!buffer)
goto close_file;
if (!fread(buffer, 1, file_size, file)) {
free(buffer);
return NULL;
}
close_file:
fclose(file);
return buffer;
}
void canonicalize_buffer(char* buffer)
{
for (size_t i = 0; buffer[i] != '\0'; i++)
if (buffer[i] != '\n')
buffer[i] -= '0';
}