Modularisation

This commit is contained in:
Hippolyte Chauvin 2023-12-04 11:39:25 +01:00
parent a77b52caba
commit ad5afe8c01
6 changed files with 63 additions and 41 deletions

View file

@ -1,23 +1,9 @@
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *strrev(char *to_reverse) {
size_t length = strlen(to_reverse);
int position = length - 1;
char *reversed = malloc((1 + length) * sizeof(char));
while (position >= 0) {
*reversed = to_reverse[position];
reversed++;
position--;
}
*reversed = '\0';
reversed = reversed - length;
return reversed;
}
#include "string.h"
#include "io.h"
static char first_digit(char *line) {
while (*line != '\0' && !isdigit(*line)) {
@ -31,31 +17,6 @@ static char first_digit(char *line) {
}
}
static char *read_line(FILE *input_file) {
unsigned int max_length = 16;
unsigned int current_length = 0;
char *line = malloc(max_length * sizeof(char));
int current_char = fgetc(input_file);
while (current_char != EOF && current_char != '\n') {
if (current_length == max_length) {
max_length *= 2;
line = realloc(line, max_length * sizeof(char));
}
line[current_length] = current_char;
current_length++;
current_char = fgetc(input_file);
}
if (current_length == max_length) {
line = realloc(line, (max_length + 1) * sizeof(char));
}
line[current_length] = '\0';
return line;
}
unsigned int get_calibration_sum(FILE *input_file) {
unsigned int sum = 0;
char *current_line, *reversed_line;

View file

@ -1,6 +1,8 @@
#ifndef CALIBRATION_H
#define CALIBRATION_H
#include <stdio.h>
unsigned int get_calibration_sum(FILE *input_file);
#endif /* CALIBRATION_H */

27
src/io.c Normal file
View file

@ -0,0 +1,27 @@
#include <stdio.h>
#include <stdlib.h>
char *read_line(FILE *input_file) {
unsigned int max_length = 16;
unsigned int current_length = 0;
char *line = malloc(max_length * sizeof(char));
int current_char = fgetc(input_file);
while (current_char != EOF && current_char != '\n') {
if (current_length == max_length) {
max_length *= 2;
line = realloc(line, max_length * sizeof(char));
}
line[current_length] = current_char;
current_length++;
current_char = fgetc(input_file);
}
if (current_length == max_length) {
line = realloc(line, (max_length + 1) * sizeof(char));
}
line[current_length] = '\0';
return line;
}

8
src/io.h Normal file
View file

@ -0,0 +1,8 @@
#ifndef IO_H
#define IO_H
#include <stdio.h>
char *read_line(FILE *input_file);
#endif /* IO_H */

18
src/string.c Normal file
View file

@ -0,0 +1,18 @@
#include <stdlib.h>
#include <string.h>
char *strrev(char *to_reverse) {
size_t length = strlen(to_reverse);
int position = length - 1;
char *reversed = malloc((1 + length) * sizeof(char));
while (position >= 0) {
*reversed = to_reverse[position];
reversed++;
position--;
}
*reversed = '\0';
reversed = reversed - length;
return reversed;
}

6
src/string.h Normal file
View file

@ -0,0 +1,6 @@
#ifndef STRING_H
#define STRING_H
char *strrev(char *to_reverse);
#endif /* STRING_H */