Home > Mobile >  How to clear the EOF indicator?
How to clear the EOF indicator?

Time:12-26

I am reading a text file in C. I need to find the first occurrence of a particular character ('(') from the current pointer position and move the pointer to that place. I do this by reading into a buffer and then using strchr to find the character. Then I seek to the position of the character. The issue is that if I read till the end of file into my buffer, it will set the EOF indicator. Even though I seek back to the position of the character, the EOF indicator is set anyway and will mess with the error handling in the rest of the code. So how can I ensure that when I seek back to within the file's contents, EOF is set to false?

int io_read_until_char(char stopchar, FILE * ifile)
{
    char row[MAXCHAR];
    int offset, read_len;
    char * loc = NULL;

    while (!feof(ifile))
    {
        if(fgets(row, MAXCHAR, ifile) == NULL)
        {
            strerror(errno);
            break;
        }
        read_len = strlen(row);
        loc = strchr(row, stopchar);
        if(loc == NULL)
            continue;
        else
        {
            offset = -read_len   (int)(loc - row);
            fseek(ifile, offset, SEEK_CUR);
            break;
        }
    }
    if(feof(ifile) && loc == NULL)
    {
        return(-1);
    }
    else if(ferror(ifile))
    {
        perror("Error in parsing stuff!\n");
        strerror(errno);
        return(-1);
    }
    else
        return(0);
}

CodePudding user response:

To clear the end-of-file indicator of a stream, you can call the function clearerr.

However, doing this should not be necessary. When calling the function fseek, the end-of-file indicator will be automatically cleared, assuming that the function call is successful.

  • Related