FILE: improve error handling

This also fixes various valgrind warnings. We explicitly
check if we operate on a regular file instead of relying
on error handling of fopen/open.
This commit is contained in:
hasufell 2014-06-28 00:48:54 +02:00
parent 913a585279
commit fd978fcfec
No known key found for this signature in database
GPG Key ID: 220CD1C5BDEED020
1 changed files with 18 additions and 0 deletions

View File

@ -56,8 +56,19 @@ read_file(char const * const filename)
ssize_t n;
size_t file_length = 0;
string *result_string;
struct stat s;
if (!filename)
return NULL;
fd = open(filename, O_RDONLY);
/* check if this is a real file */
if (fstat(fd, &s) == -1)
return NULL;
if (!S_ISREG(s.st_mode))
return NULL;
file_length = lseek(fd, 0, SEEK_END) + 1;
lseek(fd, 0, SEEK_SET);
@ -107,10 +118,17 @@ bool
write_file(string const *wstring, char const * const filename)
{
FILE *fp;
struct stat s;
if (!wstring || !filename)
return false;
/* if "filename" already exists, we need to make sure
* it's a regular file */
if (stat(filename, &s) == 0 &&
!S_ISREG(s.st_mode))
return false;
fp = fopen(filename, "w");
if (!fp) {