Systems IO
Binary Read Count
The count returned by fread tells the loop how many binary items were loaded.
Binary Read Count
binary_read_count.c
#include <stdio.h>
int main(void) {
int count = ;
int values[4] = {2, 4, 6, 8};
int loaded[4] = {0, 0, 0, 0};
int sum = 0;
FILE *out = fopen("egtry_c17_count.bin", "wb");
fwrite(values, sizeof(values[0]), count, out);
fclose(out);
FILE *in = fopen("egtry_c17_count.bin", "rb");
int read = (int)fread(loaded, sizeof(loaded[0]), 4, in);
fclose(in);
remove("egtry_c17_count.bin");
for (int i = 0; i < read; i++) {
sum = sum + loaded[i];
}
printf("read=%d sum=%d\n", read, sum);
return 0;
}
#include <stdio.h>
int main(void) {
int count = ;
int values[4] = {2, 4, 6, 8};
int loaded[4] = {0, 0, 0, 0};
int sum = 0;
FILE *out = fopen("egtry_c17_count.bin", "wb");
fwrite(values, sizeof(values[0]), count, out);
fclose(out);
FILE *in = fopen("egtry_c17_count.bin", "rb");
int read = (int)fread(loaded, sizeof(loaded[0]), 4, in);
fclose(in);
remove("egtry_c17_count.bin");
for (int i = 0; i < read; i++) {
sum = sum + loaded[i];
}
printf("read=%d sum=%d\n", read, sum);
return 0;
}
#include <stdio.h>
int main(void) {
int count = ;
int values[4] = {2, 4, 6, 8};
int loaded[4] = {0, 0, 0, 0};
int sum = 0;
FILE *out = fopen("egtry_c17_count.bin", "wb");
fwrite(values, sizeof(values[0]), count, out);
fclose(out);
FILE *in = fopen("egtry_c17_count.bin", "rb");
int read = (int)fread(loaded, sizeof(loaded[0]), 4, in);
fclose(in);
remove("egtry_c17_count.bin");
for (int i = 0; i < read; i++) {
sum = sum + loaded[i];
}
printf("read=%d sum=%d\n", read, sum);
return 0;
}
read count
The returned item count is safer than assuming the full buffer was filled.
bounded loop
The sum loop uses the returned count as its upper bound.