diff options
author | khali <khali> | 2015-04-21 07:04:27 +0000 |
---|---|---|
committer | khali <khali> | 2015-04-21 07:04:27 +0000 |
commit | b4f32bd3341060d1ee2b3424e9e73b679299a98b (patch) | |
tree | e5c017f41376702cd5f8e2b7ca8dd4b2e175c3e1 /util.c | |
parent | ad44e864c38f2a1d32c9b2ab1c633067d003333e (diff) | |
download | dmidecode-b4f32bd3341060d1ee2b3424e9e73b679299a98b.tar.gz |
util: Add read_file() function for reading sysfs files
Add a function that can read a complete, unknown size file for
reading entry point files from sysfs. This function models its signature
on the mem_chunk() funtion, so it also allocates memory that the caller
needs to free. The files that we are interested in reading are very small,
and have a known upper bound on the size. The EINTR handling is based
on the myread() function.
Contributed by Roy Franz.
Diffstat (limited to 'util.c')
-rw-r--r-- | util.c | 55 |
1 files changed, 55 insertions, 0 deletions
@@ -89,6 +89,61 @@ int checksum(const u8 *buf, size_t len) } /* + * Reads all of file, up to max_len bytes. + * A buffer of max_len bytes is allocated by this function, and + * needs to be freed by the caller. + * This provides a similar usage model to mem_chunk() + * + * Returns pointer to buffer of max_len bytes, or NULL on error + * + */ +void *read_file(size_t max_len, const char *filename) +{ + int fd; + size_t r2 = 0; + ssize_t r; + u8 *p; + + /* + * Don't print error message on missing file, as we will try to read + * files that may or may not be present. + */ + if ((fd = open(filename, O_RDONLY)) == -1) + { + if (errno != ENOENT) + perror(filename); + return(NULL); + } + + if ((p = malloc(max_len)) == NULL) + { + perror("malloc"); + return NULL; + } + + do + { + r = read(fd, p + r2, max_len - r2); + if (r == -1) + { + if (errno != EINTR) + { + close(fd); + perror(filename); + free(p); + return NULL; + } + } + else + r2 += r; + } + while (r != 0); + + close(fd); + return p; +} + +/* * Copy a physical memory chunk into a memory buffer. * This function allocates memory. */ |