I'm taking my first C programming course and I've run into a problem trying to write a function that reads a text file one line at a time. Here's my code:
#define LINELENGTH 81
int getLine(char* line, FILE* file) {
if (line == NULL) {
line = malloc(sizeof(char) * LINELENGTH);
}
fgets(line, LINELENGTH, file);
int length = strcspn(line, "\n");
if (line[length] == '\n') {
line[length] = '\0';
line = realloc(line, sizeof(char) * (length + 1));
return length;
} else {
char* addThis = NULL;
int addedLength = getLine(addThis, file);
length += addedLength;
line = realloc(line, sizeof(char) * length);
strcat(line, addThis);
free(addThis);
addThis = NULL;
return length;
}
}
int main() {
FILE *text = fopen("test.txt", "r");
char* line = NULL;
getLine(line, text);
printf("The first line is \"%s\"", line);
fclose(text);
free(line);
return 0;
}
My test input file right now just contains a single line, "test"
When I run the program I get "The first line is "(null)"". Not what I was hoping for. When I step thru the function in the debugger everything appears to be working fine inside getLine. But when the function returns all I have left is null.
Any help is appreciated. Thanks.