Reading and writing integers to a binary file using C?

情到浓时终转凉″ 提交于 2019-12-11 04:55:52

问题


I am trying to write 100 integers to binary file. 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);
            return EXIT_FAILURE;
    }
    fread(&num, sizeof(int), 1, file);
    printf("%d", num);
}

My output is like this:

-13421772802147469895-168955699232767012640583688388440-104919389914260634872147467638000128293273683884400-19797114882147440795-168947558432767-1097029212883066888388440148657280313254001912147440795-168942592032767-109702911303445504838844014865730434362077432147440795-168935577632767-1097029063753420883766251486573257-6039796492147440795-168932864032767-109702901326841856838844014865733541270-168949760032767-10970289133241241683884401486573450-1090518913214744079500196944831217016018891752457584192041348617175279241952408940298110176910929517683167731702125413116313304413809989891296126535181930809719192433591818324585127960891517680423011935761967-13421772802147469895-168955699232767012640583688388440-104919389914260634872147467638000128293273683884400-19797114882147440795-168947558432767

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.


回答1:


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.



来源:https://stackoverflow.com/questions/40810314/reading-and-writing-integers-to-a-binary-file-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!