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.\"
Some things wrong with the example:
fprintf(stderr, ....
fgetc()
rather than getc()
. getc()
is a macro, fgetc()
is a proper functiongetc()
returns an int
so ch
should be declared as an int
. This is important since the comparison with EOF
will be handled correctly. Some 8 bit character sets use 0xFF
as a valid character (ISO-LATIN-1 would be an example) and EOF
which is -1, will be 0xFF
if assigned to a char
.There is a potential buffer overflow at the line
lineBuffer[count] = '\0';
If the line is exactly 128 characters long, count
is 128 at the point that gets executed.
As others have pointed out, line
is a locally declared array. You can't return a pointer to it.
strncpy(count + 1)
will copy at most count + 1
characters but will terminate if it hits '\0'
Because you set lineBuffer[count]
to '\0'
you know it will never get to count + 1
. However, if it did, it would not put a terminating '\0'
on, so you need to do it. You often see something like the following:
char buffer [BUFFER_SIZE];
strncpy(buffer, sourceString, BUFFER_SIZE - 1);
buffer[BUFFER_SIZE - 1] = '\0';
if you malloc()
a line to return (in place of your local char
array), your return type should be char*
- drop the const
.