// The return string is dynamically allocated so free it after each use! // return exact string, not just a filled buffer! char *readLine(FILE *file) { if (file == NULL) { printf("Error: file pointer is null."); exit(1); } int maximumLineLength = 128; char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength); if (lineBuffer == NULL) { printf("Error allocating memory for line buffer."); exit(1); } char ch = getc(file); // read first byte/char int count = 0; while ((ch != '\n') && (ch != EOF)) { if (count == maximumLineLength) { maximumLineLength += 128; // double the size in case of filled up buffer. lineBuffer = realloc(lineBuffer, maximumLineLength); if (lineBuffer == NULL) { printf("Error reallocating space for line buffer."); exit(1); } } lineBuffer[count] = ch; count++; ch = getc(file); } lineBuffer[count] = '\0'; // size if count + 1 here lineBuffer = realloc(lineBuffer, count+1); if (lineBuffer[0] == '\0') return NULL; return lineBuffer; }