Skip to content

Commit 2c3b1fa

Browse files
committed
Fix usages of fread and fwrite
From `man 3 fread`: > The function **fread()** does not distinguish between end-of-file and > error; callers must use `feof(3)` and `ferror(3)` to determine which > occurred. > The function **fwrite()** returns a value less than _nitems_ only if a > write error has occurred. So we don't need to loop and check for `fwrite`, since it only returns anything smaller than `size` if it failed. It also doesn't set `ferror` so that's the wrong way to test for an error. Also, while `man` says nothing about `errno`, the UNIX spec for `fread` and `fwrite` says: > Otherwise, if a read error occurs, the error indicator for the stream > is set and _errno_ is set to indicate the error. (See [here](https://pubs.opengroup.org/onlinepubs/7908799/xsh/fread.html)) So I removed the TODO comment about it.
1 parent 27ccae4 commit 2c3b1fa

File tree

1 file changed

+4
-11
lines changed

1 file changed

+4
-11
lines changed

nob.h

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1756,7 +1756,6 @@ NOBDEF bool nob_write_entire_file(const char *path, const void *data, size_t siz
17561756
{
17571757
bool result = true;
17581758

1759-
const char *buf = NULL;
17601759
FILE *f = fopen(path, "wb");
17611760
if (f == NULL) {
17621761
nob_log(NOB_ERROR, "Could not open file %s for writing: %s\n", path, strerror(errno));
@@ -1769,15 +1768,10 @@ NOBDEF bool nob_write_entire_file(const char *path, const void *data, size_t siz
17691768
// ^
17701769
// data
17711770

1772-
buf = (const char*)data;
1773-
while (size > 0) {
1774-
size_t n = fwrite(buf, 1, size, f);
1775-
if (ferror(f)) {
1776-
nob_log(NOB_ERROR, "Could not write into file %s: %s\n", path, strerror(errno));
1777-
nob_return_defer(false);
1778-
}
1779-
size -= n;
1780-
buf += n;
1771+
size_t n = fwrite(data, 1, size, f);
1772+
if (n < size) {
1773+
nob_log(NOB_ERROR, "Could not write into file %s: %s\n", path, strerror(errno));
1774+
nob_return_defer(false);
17811775
}
17821776

17831777
defer:
@@ -2102,7 +2096,6 @@ NOBDEF bool nob_read_entire_file(const char *path, Nob_String_Builder *sb)
21022096

21032097
fread(sb->items + sb->count, m, 1, f);
21042098
if (ferror(f)) {
2105-
// TODO: Afaik, ferror does not set errno. So the error reporting in defer is not correct in this case.
21062099
nob_return_defer(false);
21072100
}
21082101
sb->count = new_count;

0 commit comments

Comments
 (0)