The strange behavior of 'read' system function

Vladislav Kolesnikov

The programm I tried writing should have been able to read a string of a length not longer than 8 characters and check if such string were present in the file. I decided to use 'read' system function for it, but I've come up with a strange behavior of this function. As it's written in manual, it must return 0 when the end of file is reached, but in my case when there were no more characters to read it still read a '\n' and returned 1 (number of bytes read) (I've checked the ASCII code of the read character and it's actually 10 which is of '\n'). So considering this fact I changed my code and it worked, but I still can't understand why does it behave in this way. Here is the code of my function:

int is_present(int fd, char *string)
{
    int i;
    char ch, buf[9];

    if (!read(fd, &ch, 1)) //file is empty
        return 0;

    while (1) {
        i = 0;
        while (ch != '\n') {
            buf[i++] = ch;
            read(fd, &ch, 1);
        }
        buf[i] = '\0';
        if (!strncmp(string, buf, strlen(buf))) {
            close(fd);
            return 1;
        }
        if(!read(fd, &ch, 1)) //EOF reached
            break;
    }
    close(fd);
    return 0;
}
rodrigo

I think that your problem is in the inner read() call. There you are not checking the return of the function.

    while (ch != '\n') {
        buf[i++] = ch;
        read(fd, &ch, 1);
    }

If the file happens to be at EOF when entering the function and ch equals '\n' then it will be an infinite loop, because read() will not modify the ch value. BTW, you are not checking the bounds of buf.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related