aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/file.c
diff options
context:
space:
mode:
authorEgor Tensin <Egor.Tensin@gmail.com>2023-05-13 10:58:41 +0200
committerEgor Tensin <Egor.Tensin@gmail.com>2023-05-13 11:37:46 +0200
commitcd917f48454875ad6b7fc69455281d72760c44ee (patch)
tree70a7a43fe43b7f893468f9120def5513774a242c /src/file.c
parentadd command module to handle request-response communications (diff)
downloadcimple-cd917f48454875ad6b7fc69455281d72760c44ee.tar.gz
cimple-cd917f48454875ad6b7fc69455281d72760c44ee.zip
best practices & coding style fixes
* I don't really need to declare all variables at the top of the function anymore. * Default-initialize variables more. * Don't set the output parameter until the object is completely constructed.
Diffstat (limited to '')
-rw-r--r--src/file.c23
1 files changed, 13 insertions, 10 deletions
diff --git a/src/file.c b/src/file.c
index bc7af8e..cea6794 100644
--- a/src/file.c
+++ b/src/file.c
@@ -104,14 +104,14 @@ int file_exists(const char *path)
return !ret && S_ISREG(stat.st_mode);
}
-int file_read(int fd, char **output, size_t *len)
+int file_read(int fd, char **_contents, size_t *_len)
{
char buf[128];
size_t buf_len = sizeof(buf) / sizeof(buf[0]);
int ret = 0;
- *output = NULL;
- *len = 0;
+ char *contents = NULL;
+ size_t len = 0;
while (1) {
ssize_t read_now = read(fd, buf, buf_len);
@@ -122,21 +122,24 @@ int file_read(int fd, char **output, size_t *len)
goto free_output;
}
- if (!read_now)
+ if (!read_now) {
+ *_contents = contents;
+ *_len = len;
goto exit;
+ }
- *output = realloc(*output, *len + read_now + 1);
- if (!*output) {
+ contents = realloc(contents, len + read_now + 1);
+ if (!contents) {
log_errno("realloc");
return -1;
}
- memcpy(*output + *len, buf, read_now);
- *len += read_now;
- *(*output + *len) = '\0';
+ memcpy(contents + len, buf, read_now);
+ len += read_now;
+ contents[len] = '\0';
}
free_output:
- free(*output);
+ free(contents);
exit:
return ret;