-#include "silcincludes.h"
-
-/* Reads a file to a buffer. The allocated buffer is returned. Length of
- the file read is returned to the return_len argument. */
-
-char *silc_file_read(const char *filename, uint32 *return_len)
-{
- int fd;
- char *buffer;
- int filelen;
-
- fd = open(filename, O_RDONLY);
- if (fd < 0) {
- if (errno == ENOENT)
- return NULL;
- SILC_LOG_ERROR(("Cannot open file %s: %s", filename, strerror(errno)));
- return NULL;
- }
-
- filelen = lseek(fd, (off_t)0L, SEEK_END);
- if (filelen < 0) {
- close(fd);
- return NULL;
- }
- if (lseek(fd, (off_t)0L, SEEK_SET) < 0) {
- close(fd);
- return NULL;
- }
-
- if (filelen < 0) {
- SILC_LOG_ERROR(("Cannot open file %s: %s", filename, strerror(errno)));
- close(fd);
- return NULL;
- }
-
- buffer = silc_calloc(filelen + 1, sizeof(char));
-
- if ((read(fd, buffer, filelen)) == -1) {
- memset(buffer, 0, sizeof(buffer));
- close(fd);
- SILC_LOG_ERROR(("Cannot read from file %s: %s", filename,
- strerror(errno)));
- return NULL;
- }
-
- close(fd);
- buffer[filelen] = EOF;
-
- if (return_len)
- *return_len = filelen;
-
- return buffer;
-}
-
-/* Writes a buffer to the file. */
-
-int silc_file_write(const char *filename, const char *buffer, uint32 len)
-{
- int fd;
-
- if ((fd = creat(filename, 0644)) == -1) {
- SILC_LOG_ERROR(("Cannot open file %s for writing: %s", filename,
- strerror(errno)));
- return -1;
- }
-
- if ((write(fd, buffer, len)) == -1) {
- SILC_LOG_ERROR(("Cannot write to file %s: %s", filename, strerror(errno)));
- close(fd);
- return -1;
- }
-
- close(fd);
-
- return 0;
-}
-
-/* Writes a buffer to the file. If the file is created specific mode is
- set to the file. */
-
-int silc_file_write_mode(const char *filename, const char *buffer,
- uint32 len, int mode)
-{
- int fd;
-
- if ((fd = creat(filename, mode)) == -1) {
- SILC_LOG_ERROR(("Cannot open file %s for writing: %s", filename,
- strerror(errno)));
- return -1;
- }
-
- if ((write(fd, buffer, len)) == -1) {
- SILC_LOG_ERROR(("Cannot write to file %s: %s", filename, strerror(errno)));
- close(fd);
- return -1;
- }
-
- close(fd);
-
- return 0;
-}