如何使用fread和fwrite函数来读写二进制文件?

时间:2012-02-07 16:32:14

标签: c binaryfiles fwrite fread

您好,在我的项目中,我要读取一个.bin文件,其中包含short(16 bit values)形式的传感器数据。我正在使用fread函数进入缓冲区,但我觉得读入不正确。我的意思是我写的东西和我读的东西之间没有一致性。你们能否说出这里出了什么问题?这不是我项目中的代码...我只是在这里验证freadfwrite函数。

#include<stdio.h>
void main()
{
    FILE *fp = NULL;

    short x[10] = {1,2,3,4,5,6,5000,6,-10,11};
    short result[10];

    fp=fopen("c:\\temp.bin", "wb");

    if(fp != NULL)
    {
        fwrite(x, 2 /*sizeof(short)*/, 10 /*20/2*/, fp);
        rewind(fp);
        fread(result, 2 /*sizeof(short)*/, 10 /*20/2*/, fp);
    }
    else
        exit(0);

    printf("\nResult");
    printf("\n%d",result[0]);
    printf("\n%d",result[1]);
    printf("\n%d",result[2]);
    printf("\n%d",result[3]);
    printf("\n%d",result[4]);
    printf("\n%d",result[5]);
    printf("\n%d",result[6]);
    printf("\n%d",result[7]);
    printf("\n%d",result[8]);
    printf("\n%d",result[9]);

    fclose(fp)
 }

执行fread()(HEX值)后:

temp.bin:
01 02 03 04 05 06 e1 8e 88 06 ef bf b6 0b...

在我执行fwrite()

之后
stdout:
Result
0
914
-28
-28714
-32557
1
512
-32557
908
914

2 个答案:

答案 0 :(得分:13)

以模式w+打开文件(读写)。以下代码有效:

#include<stdio.h>
int main()
{
    FILE *fp = NULL;

    short x[10] = {1,2,3,4,5,6,5000,6,-10,11};
    short result[10];
    int i;

    fp=fopen("temp.bin", "w+");

    if(fp != NULL)
    {
        fwrite(x, sizeof(short), 10 /*20/2*/, fp);
        rewind(fp);
        fread(result, sizeof(short), 10 /*20/2*/, fp);
    }
    else
        return 1;

    printf("Result\n");
    for (i = 0; i < 10; i++)
        printf("%d = %d\n", i, (int)result[i]);

    fclose(fp);
    return 0;
}

输出:

Result
0 = 1
1 = 2
2 = 3
3 = 4
4 = 5
5 = 6
6 = 5000
7 = 6
8 = -10
9 = 11

答案 1 :(得分:3)

当您打开文件时,您忘了允许阅读:

fp=fopen("c:\\temp.bin", "wb");

应该是:

fp=fopen("c:\\temp.bin", "w+b");