HelloC/readfile.c
2023-11-25 19:27:12 +01:00

61 lines
1.5 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const unsigned MAX_BUFFER_LENGTH = 256;
void trim(char *string) {
if (string[strlen(string) - 1] == '\n') {
string[strlen(string) - 1] = '\0';
trim(string);
}
}
int main() {
char *filename = "test/text1.txt";
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening file %s\n", filename);
return EXIT_FAILURE;
}
char buffer[MAX_BUFFER_LENGTH];
char *line = NULL;
while (fgets(buffer, MAX_BUFFER_LENGTH, fp)) {
trim(buffer);
char *tmpLine;
if (line == NULL) {
int newLineSize = strlen(buffer);
printf("line is null; new size %d\n", newLineSize);
tmpLine = calloc(sizeof(char), newLineSize + 1);
} else {
int newLineSize = strlen(buffer) + strlen(line);
printf("line is NOT null; new size %d\n", newLineSize);
tmpLine = realloc(line, newLineSize + 1);
}
if (tmpLine != NULL) {
line = tmpLine;
} else {
return 1;
}
strcat(line, buffer);
// check for possible overflow
if (strlen(buffer) + 1 >= MAX_BUFFER_LENGTH) {
// no edge limit problem because trim is cutting buffer if there is a "\n" on the end
printf("!!!Overflow detected!!!\n");
} else {
printf("read line (%ld): %s\n", strlen(line), line);
free(line);
line = NULL;
}
}
fclose(fp);
return EXIT_SUCCESS;
}