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
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <err.h>
#include "input.h"
size_t count_lines(FILE* file) {
size_t lineCount = 0;
char currentChar;
// on part du debut
// TODO verifier le code de retour
fseek(file, 0, SEEK_SET);
while((currentChar=fgetc(file)) != EOF) {
if(currentChar == '\n')
lineCount++;
}
return lineCount;
}
void input_int_read(struct input_int* result, char* filename) {
// open input file
FILE* file=fopen(filename, "r");
if(file == NULL)
err(1, "cannot open file %s\n", filename);
// compute line count
result->line_count = count_lines(file);
// read each line of the file
// TODO check return code
fseek(file, 0, SEEK_SET);
int current;
result->lines = malloc(result->line_count * sizeof(int));
for(size_t lineIndex = 0; lineIndex < result->line_count; lineIndex++) {
if(fscanf(file, "%d", ¤t) != 1)
err(1, "parsing error line %ld\n", lineIndex);
result->lines[lineIndex] = current;
}
// close file
fclose(file);
}
int str_replace(char* string, char a, char b) {
size_t i = 0;
int replace_count = 0;
while(string[i] != '\0') {
if(string[i] == a) {
string[i] = b;
replace_count++;
}
i++;
}
return replace_count;
}
void input_str_read(struct input_str* result, char* filename) {
// open input file
FILE* file=fopen(filename, "r");
if(file == NULL)
err(1, "cannot open file %s\n", filename);
// compute line count
result->line_count = count_lines(file);
// read each line of the file
// TODO check return code
fseek(file, 0, SEEK_SET);
size_t lineSize = 0;
result->lines = malloc(result->line_count * sizeof(char*));
for(size_t lineIndex = 0; lineIndex < result->line_count; lineIndex++) {
char** dst = &(result->lines[lineIndex]);
if(getline(dst, &lineSize, file) < 0)
err(1, "read error line %ld\n", lineIndex);
// cleanup line end char
str_replace(result->lines[lineIndex], '\n', '\0');
}
fclose(file);
}
void input_int_free(struct input_int* input) {
free(input->lines);
}
void input_str_free(struct input_str* input) {
for(size_t i = 0; i < input->line_count; i++) {
free(input->lines[i]);
}
free(input->lines);
}
|