| 1 |
#include <stdio.h> |
| 2 |
#include <string.h> |
| 3 |
#include <errno.h> |
| 4 |
|
| 5 |
#include <netpbm/pm.h> |
| 6 |
|
| 7 |
#include "stdio_nofail.h" |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
size_t |
| 12 |
fread_or_eof_nofail(void * const ptr, |
| 13 |
size_t const size, |
| 14 |
size_t const nmemb, |
| 15 |
FILE * const streamP) { |
| 16 |
|
| 17 |
size_t rc; |
| 18 |
|
| 19 |
rc = fread(ptr, size, nmemb, streamP); |
| 20 |
|
| 21 |
if (rc < nmemb) { |
| 22 |
if (!feof(streamP)) |
| 23 |
pm_error("File read failed. Errno=%d (%s)", |
| 24 |
errno, strerror(errno)); |
| 25 |
} |
| 26 |
return rc; |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
void |
| 32 |
fread_nofail(void * const ptr, |
| 33 |
size_t const size, |
| 34 |
size_t const nmemb, |
| 35 |
FILE * const streamP) { |
| 36 |
|
| 37 |
size_t rc; |
| 38 |
|
| 39 |
rc = fread(ptr, size, nmemb, streamP); |
| 40 |
|
| 41 |
if (rc < nmemb) { |
| 42 |
if (feof(streamP)) |
| 43 |
pm_error("File read failed. Premature end of file"); |
| 44 |
else |
| 45 |
pm_error("File read failed. Errno=%d (%s)", |
| 46 |
errno, strerror(errno)); |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
int |
| 53 |
fgetc_nofail(FILE * streamP) { |
| 54 |
|
| 55 |
int rc; |
| 56 |
|
| 57 |
rc = fgetc(streamP); |
| 58 |
|
| 59 |
if (rc == EOF) { |
| 60 |
if (feof(streamP)) |
| 61 |
pm_error("File read failed. Premature end of file"); |
| 62 |
else |
| 63 |
pm_error("File read failed. Errno=%d (%s)", |
| 64 |
errno, strerror(errno)); |
| 65 |
} |
| 66 |
return rc; |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
int |
| 72 |
fseek_nofail(FILE * const streamP, |
| 73 |
long const offset, |
| 74 |
int const whence) { |
| 75 |
|
| 76 |
int rc; |
| 77 |
|
| 78 |
rc = fseek(streamP, offset, whence); |
| 79 |
|
| 80 |
if (rc < 0) |
| 81 |
pm_error("File seek failed. Errno=%d (%s)", errno, strerror(errno)); |
| 82 |
|
| 83 |
return rc; |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
long |
| 89 |
ftell_nofail(FILE * const streamP) { |
| 90 |
|
| 91 |
long rc; |
| 92 |
|
| 93 |
rc = ftell(streamP); |
| 94 |
|
| 95 |
if (rc < 0) |
| 96 |
pm_error("File position query failed. Errno=%d (%s)", |
| 97 |
errno, strerror(errno)); |
| 98 |
|
| 99 |
return rc; |
| 100 |
} |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
char * |
| 105 |
fgets_nofail(char * const s, |
| 106 |
int const size, |
| 107 |
FILE * const streamP) { |
| 108 |
|
| 109 |
char * rc; |
| 110 |
|
| 111 |
rc = fgets(s, size, streamP); |
| 112 |
|
| 113 |
if (ferror(streamP)) |
| 114 |
pm_error("File read failed. Errno=%d (%s)", errno, strerror(errno)); |
| 115 |
|
| 116 |
return rc; |
| 117 |
} |
| 118 |
|
| 119 |
|
| 120 |
|