TimelordViktorious TimelordViktorious - 9 months ago 58
C Question

Writing integers to a binary file

I am trying to write 100 integers to binary file in order to test out something.

I have tried writing to this file, and reading from it. When reading from it I get completely random digits.

Here is the block concerning the write.

Do note I have the file open for write with "wb" mode. I have also closed the file at the end.

for (int i = 0; i < 99; i++) {
fwrite(&i, sizeof(int), 1, file);

Here is the block concerning the read.
Do note I do have the file open here in "rb" mode and it is closed.

int num;
for (int i = 0; i < 100; i++) {
int rc = getc(file);
if (rc == EOF) {
fputs("Error occured while reading file", stderr);
fread(&num, sizeof(int), 1, file);
printf("%d", num);

My output is like this:


So there is something wrong, and I am not sure what exactly. Perhaps I am not sure if I understand the API for reading/writing completely (specifically size_t nitems)? I am not sure how to tell how many bytes I need to read/write from a file.

Answer Source

In the first loop, you are writing 100 integers starting at the address of 'i', 99 times.

Not what I think you were thinking you were doing.

it should be

fwrite(&i, sizeof(int), 1, file);

Secondly, what mode do you open the file for writing? It should be opened in binary mode otherwise it will not save binary data correctly (add 'b' to the fopen mode value)

DO you close and reopen the file for the read (and set the right file mode?) or if I was left open, do you fseek back to beginning of the file before trying to read the values.