lkml.org 
[lkml]   [2020]   [May]   [19]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
Date
From
SubjectRe: [PATCH 03/29] modpost: add read_text_file() and get_line() helpers
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;
> +}

\
 
 \ /
  Last update: 2020-05-19 12:22    [W:0.142 / U:0.032 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site