summaryrefslogtreecommitdiff
path: root/input.c
blob: 5a3500a3d3dfa8347c5f995052c9d3fc42e6b516 (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
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
#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", &current) != 1)
			err(1, "parsing error line %ld\n", lineIndex);
			
		result->lines[lineIndex] = current;
	}

	// close file
	fclose(file);
}

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);
	}

	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);
}

char* copy_line(char* line) {
	int len = strlen(line);
	char* copy = malloc(len * sizeof(char));
	if(copy == NULL)
		err(1, "malloc error");
	memset(copy, '\0', len);
	strncpy(copy, line, len);
	return copy;
}