Optimize file reading function
Former-commit-id: fd7b0850c404210c9cb73d698e3750ef656f2f78
This commit is contained in:
parent
a9ddb5622b
commit
a2ce97bef9
@ -76,8 +76,13 @@ char *read_file(char const * const filename)
|
|||||||
int fd = 0;
|
int fd = 0;
|
||||||
size_t str_size = 0;
|
size_t str_size = 0;
|
||||||
ssize_t n;
|
ssize_t n;
|
||||||
|
size_t file_length = 0;
|
||||||
|
|
||||||
fd = open(filename, O_RDONLY);
|
fd = open(filename, O_RDONLY);
|
||||||
|
file_length = lseek(fd, 0, SEEK_END) + 1;
|
||||||
|
lseek(fd, 0, SEEK_SET);
|
||||||
|
|
||||||
|
string = malloc(sizeof(char) * file_length);
|
||||||
|
|
||||||
if (fd != -1) {
|
if (fd != -1) {
|
||||||
/* read and copy chunks */
|
/* read and copy chunks */
|
||||||
@ -88,11 +93,6 @@ char *read_file(char const * const filename)
|
|||||||
|
|
||||||
str_size += n; /* count total bytes read */
|
str_size += n; /* count total bytes read */
|
||||||
|
|
||||||
REALLOC( /* allocate correct size */
|
|
||||||
string, /* pointer to realloc */
|
|
||||||
str_size /* total bytes read */
|
|
||||||
+ 1); /* space for trailing NULL byte */
|
|
||||||
|
|
||||||
/* append buffer to string */
|
/* append buffer to string */
|
||||||
memcpy(string + (str_size - n), buf, (size_t)n);
|
memcpy(string + (str_size - n), buf, (size_t)n);
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user