[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[dmidecode] [PATCH 1/4] add read_file() function for reading sysfs files
From: |
Roy Franz |
Subject: |
[dmidecode] [PATCH 1/4] add read_file() function for reading sysfs files |
Date: |
Fri, 17 Apr 2015 11:36:30 -0700 |
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.
Signed-off-by: Roy Franz <address@hidden>
---
util.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++
util.h | 1 +
2 files changed, 51 insertions(+)
diff --git a/util.c b/util.c
index 2ab4915..4efff98 100644
--- a/util.c
+++ b/util.c
@@ -77,6 +77,56 @@ static int myread(int fd, u8 *buf, size_t count, const char
*prefix)
return 0;
}
+/*
+ * 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;
+
+ 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;
+}
int checksum(const u8 *buf, size_t len)
{
diff --git a/util.h b/util.h
index e564292..ca8080e 100644
--- a/util.h
+++ b/util.h
@@ -28,3 +28,4 @@ int checksum(const u8 *buf, size_t len);
void *mem_chunk(size_t base, size_t len, const char *devmem);
int write_dump(size_t base, size_t len, const void *data, const char
*dumpfile, int add);
u64 u64_range(u64 start, u64 end);
+void *read_file(size_t len, const char *filename);
--
1.9.1