|
13 | 13 | #include <sys/stat.h>
|
14 | 14 | #include <unistd.h>
|
15 | 15 |
|
| 16 | +/* |
| 17 | + * Read a file into memory. |
| 18 | + * The file contents are returned in a malloc'd buffer, and *filesize |
| 19 | + * is set to the length of the file. |
| 20 | + * |
| 21 | + * The returned buffer is always zero-terminated; the size of the returned |
| 22 | + * buffer is actually *filesize + 1. That's handy when reading a text file. |
| 23 | + * This function can be used to read binary files as well, you can just |
| 24 | + * ignore the zero-terminator in that case. |
| 25 | + * |
| 26 | + */ |
| 27 | +char * |
| 28 | +slurpFileFullPath(const char *from_fullpath, size_t *filesize, bool safe, fio_location location) |
| 29 | +{ |
| 30 | + int fd; |
| 31 | + char *buffer; |
| 32 | + int len; |
| 33 | + struct stat statbuf; |
| 34 | + |
| 35 | + if ((fd = fio_open(from_fullpath, O_RDONLY | PG_BINARY, location)) == -1) |
| 36 | + { |
| 37 | + if (safe) |
| 38 | + return NULL; |
| 39 | + else |
| 40 | + elog(ERROR, "Could not open file \"%s\" for reading: %s", |
| 41 | + from_fullpath, strerror(errno)); |
| 42 | + } |
| 43 | + |
| 44 | + if (fio_fstat(fd, &statbuf) < 0) |
| 45 | + { |
| 46 | + if (safe) |
| 47 | + return NULL; |
| 48 | + else |
| 49 | + elog(ERROR, "Could not stat file \"%s\": %s", |
| 50 | + from_fullpath, strerror(errno)); |
| 51 | + } |
| 52 | + |
| 53 | + len = statbuf.st_size; |
| 54 | + |
| 55 | + buffer = pg_malloc(len + 1); |
| 56 | + |
| 57 | + if (fio_read(fd, buffer, len) != len) |
| 58 | + { |
| 59 | + if (safe) |
| 60 | + return NULL; |
| 61 | + else |
| 62 | + elog(ERROR, "Could not read file \"%s\": %s\n", |
| 63 | + from_fullpath, strerror(errno)); |
| 64 | + } |
| 65 | + |
| 66 | + fio_close(fd); |
| 67 | + |
| 68 | + /* Zero-terminate the buffer. */ |
| 69 | + buffer[len] = '\0'; |
| 70 | + |
| 71 | + if (filesize) |
| 72 | + *filesize = len; |
| 73 | + |
| 74 | + return buffer; |
| 75 | +} |
| 76 | + |
16 | 77 | /*
|
17 | 78 | * Read a file into memory. The file to be read is <datadir>/<path>.
|
18 | 79 | * The file contents are returned in a malloc'd buffer, and *filesize
|
|
0 commit comments