On Sun, May 17, 2020 at 06:48:33PM +0900, Masahiro Yamada wrote:

> +char *read_text_file(const char *filename)
> +{
> +     struct stat st;
> +     int fd;
> +     char *buf;
> +
> +     fd = open(filename, O_RDONLY);
> +     if (fd < 0)
> +             return NULL;
> +
> +     if (fstat(fd, &st) < 0)
> +             return NULL;
> +
> +     buf = NOFAIL(malloc(st.st_size + 1));
> +
> +     if (read(fd, buf, st.st_size) != st.st_size) {

Is this sensible coding ? I've always been taught read() can return
early/short for a number of reasons and we must not assume this is an
error.

The 'normal' way to read a file is something like:

        for (;;) {
                ssize_t ret = read(fd, buf + size, st.st_size - size);
                if (ret < 0) {
                        free(buf);
                        buf = NULL;
                        goto close;
                }
                if (!ret)
                        break;

                size += ret;
        }

> +             free(buf);
> +             buf = NULL;
> +             goto close;
> +     }
> +     buf[st.st_size] = '\0';
> +close:
> +     close(fd);
> +
> +     return buf;
> +}

Reply via email to