I wrote this function to read a line from a file:
const char *readLine(FILE *file) {
if (file == NULL) {
printf(\"Error: file pointer is null.\"
const char *readLine(FILE *file, char* line) {
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);
int count = 0;
while ((ch != '\n') && (ch != EOF)) {
if (count == maximumLineLength) {
maximumLineLength += 128;
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';
char line[count + 1];
strncpy(line, lineBuffer, (count + 1));
free(lineBuffer);
return line;
}
char linebuffer[256];
while (!feof(myFile)) {
const char *line = readLine(myFile, linebuffer);
printf("%s\n", line);
}
note that the 'line' variable is declared in calling function and then passed, so your readLine
function fills predefined buffer and just returns it. This is the way most of C libraries work.
There are other ways, which I'm aware of:
char line[]
as static
(static char line[MAX_LINE_LENGTH]
-> it will hold it's value AFTER returning from the function). -> bad,
the function is not reentrant, and
race condition can occur -> if you
call it twice from two threads, it
will overwrite it's resultsmalloc()
ing the char line[], and
freeing it in calling functions ->
too many expensive malloc
s, and,
delegating the responsibility to free the buffer to another function (the most elegant solution is to call malloc
and free
on any buffers in same function)btw, 'explicit' casting from char*
to const char*
is redundant.
btw2, there is no need to malloc()
the lineBuffer, just define it char lineBuffer[128]
, so you don't need to free it
btw3 do not use 'dynamic sized stack arrays' (defining the array as char arrayName[some_nonconstant_variable]
), if you don't exactly know what are you doing, it works only in C99.