summaryrefslogtreecommitdiff
path: root/input.c
diff options
context:
space:
mode:
Diffstat (limited to 'input.c')
-rw-r--r--input.c65
1 files changed, 42 insertions, 23 deletions
diff --git a/input.c b/input.c
index 5d184bb..1c72194 100644
--- a/input.c
+++ b/input.c
@@ -2,8 +2,9 @@
#include <stdio.h>
#include <string.h>
#include <err.h>
+#include "input.h"
-/*public*/size_t count_lines(FILE* file) {
+size_t count_lines(FILE* file) {
size_t lineCount = 0;
char currentChar;
// on part du debut
@@ -16,40 +17,58 @@
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
+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;
- 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;
+ 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;
}
- return 0;
+ // close file
+ fclose(file);
}
-/*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
+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;
- for(int lineIndex = 0; lineIndex < resultSize; lineIndex++) {
- char** dst = &result[lineIndex];
+ 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, "Erreur de lecture ligne %d\n", lineIndex);
+ err(1, "read error line %ld\n", lineIndex);
}
- return 0;
+ fclose(file);
+}
+
+void input_int_free(struct input_int* input) {
+ free(input->lines);
}
-/*public*/void free_strings(char** strings, size_t stringCount) {
- for(size_t i = 0; i < stringCount; i++) {
- free(strings[i]);
+void input_str_free(struct input_str* input) {
+ for(size_t i = 0; i < input->line_count; i++) {
+ free(input->lines[i]);
}
- free(strings);
+ free(input->lines);
}