summaryrefslogtreecommitdiff
path: root/input.c
blob: 5d184bb467cf5cfade0a4694b2609cc5251cb7f7 (plain)
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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <err.h>

/*public*/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;
}

/*public*/int read_lines_as_int(FILE* file, int* result, int resultSize) {
	// retour au debut du fichier et lecture des lignes
	// TODO verifier le code de retour
	fseek(file, 0, SEEK_SET);
	int current;
	for(int lineIndex = 0; lineIndex < resultSize; lineIndex++) {
		if(fscanf(file, "%d", &current) != 1) {
			result[lineIndex] = 0;
			printf("Erreur de lecture ligne %d\n", lineIndex);
			continue;
		}
		result[lineIndex] = current;
	}

	return 0;
}

/*public*/int read_lines_as_string(FILE* file, char** result, int resultSize) {
	// retour au debut du fichier et lecture des lignes
	// TODO verifier le code de retour
	fseek(file, 0, SEEK_SET);
	size_t lineSize = 0;
	for(int lineIndex = 0; lineIndex < resultSize; lineIndex++) {
		char** dst = &result[lineIndex];
		if(getline(dst, &lineSize, file) < 0)
			err(1, "Erreur de lecture ligne %d\n", lineIndex);
	}

	return 0;
}

/*public*/void free_strings(char** strings, size_t stringCount) {
	for(size_t i = 0; i < stringCount; i++) {
		free(strings[i]);
	}
	free(strings);
}