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