bawejakunal bawejakunal - 3 months ago 9
C Question

Determine EOF while reading file of unknown line lengths

/* Utility function to read lines of unknown lengths */
char *readline(FILE* fp, int max_length)
{
//The size is extended by the input with the value of the provisional
char *str;
int ch;
int len = 0;
int current_max = max_length;

str = (char*)malloc(sizeof(char)*current_max);
if(!str)
return str;

while((char)(ch = fgetc(fp))!='\n' && ch != EOF)
{
str[len++] = ch;
if(len == current_max)
{
current_max = current_max + max_length;
str = realloc(str, sizeof(char)*current_max);
if(!str)
return str;
}
}
str[len] = '\0';

return str;
}


I have the above code snippet to read a line of unknown length. I am able to read single line inputs, as expected from stdin, but while reading a file I am having trouble in determining the EOF of the file.

While reading from a file, I am reading it line by line in a loop, now I want to break off the loop once all lines have been read but I am not able to determine when to do so, hence the loop ends up executing forever. Please help me with determining the break condition.

char *line;

while(1)
{
line = readline(fd, MAX_INPUT_LENGTH);

/*IF all lines have been read then break off the loop, basically determine EOF ?*

//text processing on the line

}

Answer

Try:

while((ch = fgetc(fp))!=EOF)
{
    if (ch=='\n') {
        str[len]='\0';
        return(str);
    }
    str[len++] = ch;
}
str[len]= '\0';
return(str);

This separates EOL handling from EOF handling. After reading EOF, the next call to readline will return an empty string, the signal that EOF has been reached.