diff options
author | Lars Hjemli <hjemli@gmail.com> | 2009-08-19 00:17:41 (JST) |
---|---|---|
committer | Lars Hjemli <hjemli@gmail.com> | 2009-08-19 00:22:14 (JST) |
commit | e16f1783346a090e4ea1194dcaae7f03e813f6a2 (patch) | |
tree | 268f5ba231895ba3a63071497764c64d44733da5 /shared.c | |
parent | 523c133e2e5f7089a3d18ac23f2074b60991a7f0 (diff) | |
download | cgit-e16f1783346a090e4ea1194dcaae7f03e813f6a2.zip cgit-e16f1783346a090e4ea1194dcaae7f03e813f6a2.tar.gz |
Add and use a common readfile() function
This function is used to read the full content of a textfile into a
newly allocated buffer (with zerotermination).
It replaces the earlier readfile() in scan-tree.c (which was rather
error-prone[1]), and is reused by read_agefile() in ui-repolist.c.
1: No checks for EINTR and EAGAIN, fixed-size buffer
Signed-off-by: Lars Hjemli <hjemli@gmail.com>
Diffstat (limited to 'shared.c')
-rw-r--r-- | shared.c | 21 |
1 files changed, 21 insertions, 0 deletions
@@ -393,3 +393,24 @@ int cgit_close_filter(struct cgit_filter *filter) | |||
393 | return 0; | 393 | return 0; |
394 | die("Subprocess %s exited abnormally", filter->cmd); | 394 | die("Subprocess %s exited abnormally", filter->cmd); |
395 | } | 395 | } |
396 | |||
397 | /* Read the content of the specified file into a newly allocated buffer, | ||
398 | * zeroterminate the buffer and return 0 on success, errno otherwise. | ||
399 | */ | ||
400 | int readfile(const char *path, char **buf, size_t *size) | ||
401 | { | ||
402 | int fd; | ||
403 | struct stat st; | ||
404 | |||
405 | fd = open(path, O_RDONLY); | ||
406 | if (fd == -1) | ||
407 | return errno; | ||
408 | if (fstat(fd, &st)) | ||
409 | return errno; | ||
410 | if (!S_ISREG(st.st_mode)) | ||
411 | return EISDIR; | ||
412 | *buf = xmalloc(st.st_size + 1); | ||
413 | *size = read_in_full(fd, *buf, st.st_size); | ||
414 | (*buf)[*size] = '\0'; | ||
415 | return (*size == st.st_size ? 0 : errno); | ||
416 | } | ||