FILE: be more fault tolerant

This commit is contained in:
hasufell 2014-06-05 19:12:21 +02:00
parent 44896c0cb1
commit eef192f0cc
No known key found for this signature in database
GPG Key ID: 220CD1C5BDEED020
2 changed files with 29 additions and 10 deletions

View File

@ -62,8 +62,11 @@ read_file(char const * const filename)
/* read and copy chunks */
while ((n = read(fd, buf, STD_FILE_BUF)) != 0) {
if (n == -1)
NTRU_ABORT("Failed while reading file descriptor %d\n", fd);
if (n == -1) {
NTRU_WARN_DEBUG("Failed while reading file descriptor %d",
fd);
goto failure_cleanup;
}
str_size += n; /* count total bytes read */
@ -78,8 +81,10 @@ read_file(char const * const filename)
/* add trailing NULL byte */
cstring[str_size] = '\0';
if (close(fd))
NTRU_ABORT("Failed to close file descripter %d\n", fd);
if (close(fd)) {
NTRU_WARN_DEBUG("Failed to close file descripter %d\n", fd);
goto failure_cleanup;
}
result_string = ntru_malloc(sizeof(*result_string));
result_string->ptr = cstring;
@ -90,24 +95,35 @@ read_file(char const * const filename)
} else {
return NULL;
}
failure_cleanup:
free(cstring);
return NULL;
}
/*------------------------------------------------------------------------*/
void
bool
write_file(string const *wstring, char const * const filename)
{
FILE *fp;
fp = fopen(filename, "w");
if (!fp)
NTRU_ABORT("Failed while creating file\n");
if (!fp) {
NTRU_WARN_DEBUG("Failed while creating file\n");
return false;
}
for (uint32_t i = 0; i < wstring->len; i++)
fprintf(fp, "%c", wstring->ptr[i]);
fclose(fp);
if (fclose(fp)) {
NTRU_WARN_DEBUG("Failed to close file descripter\n");
return false;
}
return true;
}
/*------------------------------------------------------------------------*/

View File

@ -32,13 +32,15 @@
#include "ntru_common.h"
#include "ntru_string.h"
#include <stdbool.h>
/**
* Reads a file and returns a newly allocated string.
*
* @param filename file to open
* @return a newly allocated string which must be freed by the caller
* or NULL on failure
* or NULL on failure (e.g. if the file could not be opened/closed)
*/
string *
read_file(char const * const filename);
@ -49,8 +51,9 @@ read_file(char const * const filename);
*
* @param wstring the string to write to the file
* @param filename the name of the file to write to
* @return true for success or false for failure if fopen or fclose failed
*/
void
bool
write_file(string const *wstring, char const * const filename);