Skip to content

Handling of EOF in lsh_read_line() #25

@robsim0116

Description

@robsim0116

Hi :) I just wanted to contribute to your excellent tutorial by (I think) improving the error handling in lsh_read_line(). Unless I'm mistaken, I don't think it currently handles the case when EOF actually indicates a read error and not a "successful" EOF/an EOF proper. My own code for the while loop looks more or less like this at the moment (you can see I'm (a) checking for the meaning of the returned EOF and (b) ensuring the buffer is freed before exiting):

// rest of code

while (1) {
        c = getc(stdin);
        
        if (c == '\n') {
            rl_buf[pos] = '\0';
            return rl_buf;
        } else if (c == EOF && ferror(stdin)) {
            fprintf(stderr, "ERROR: read error (%d)\n", errno);
            free(rl_buf);
            exit(EXIT_FAILURE);
        } else if (c == EOF && feof(stdin)){
            free(rl_buf);
            exit(EXIT_SUCCESS);
        }

        rl_buf[pos] = c;
        pos++;
        
        // rest of code
}

What do you think? Have I made a mistake in my reasoning?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions