简体   繁体   English

从 c 中的二进制文件读取数组返回不正确的值

[英]Reading an array from a binary file in c returns incorrect values

I just started learning files in c language and i have a problem with my code.我刚开始用 c 语言学习文件,我的代码有问题。 It works just fine writing in the binary file, but when im trying to read the values back, it returns one less value and also different values for the array.它在二进制文件中写入工作正常,但是当我尝试读回值时,它返回一个少一个值以及数组的不同值。 I am aware that probably i've made a dumb mistake, if you could help me understand i would be greatful.我知道我可能犯了一个愚蠢的错误,如果你能帮助我理解我会很棒。 This is my code :这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()

{
    FILE *f;
    if ((f=fopen("fis.bin","wb"))==NULL)
    {
        printf ("Error\n");
        exit(1);
    }

    int *v;
    int n,x;
    char s[100];
    scanf("%d",&n);
    v=(int*)malloc(n*sizeof(int));

    for (int i=0; i<n; i++)
    {
        scanf("%d",&v[i]);

        x=fprintf(f,"%d\n",v[i]);
        if (x<0)
            perror("Error:");
    }
    fclose(f);

    int *cit;

    cit=(int*)calloc(n,sizeof(int));

    if ((f=fopen("fis.bin","rb"))==NULL)
    {
        printf ("Error\n");
        exit(1);
    }
    fseek(f,0,SEEK_END);

    int sz = ftell(f)/sizeof(v[0]);

    fseek(f,0,0);

    int i=0;

    if(!fread(cit,sizeof(int),sz,f))
        perror("err: ");

    for (i=0; i<sz; i++)
        printf("%d\n",cit[i]);



    printf("\n");

    free(v);
    free(cit);


    fclose(f);

}

The problem is you are writing to the file using fprintf .问题是您正在使用fprintf写入文件。

where as fprintf writes string representation of integers .其中fprintf写入integers string表示integers For example, when you write 2 to the file you are writing "2" as string of size 1 byte.例如,当您将2写入文件时,您将"2"作为大小为 1 字节的字符串写入。

x=fprintf(f,"%d\n",v[i]);

Thus replace fprintf with fwrite as below.因此,将fprintf替换为fwrite ,如下所示。

fwrite(&v[i], sizeof(v[0]), 1, f);

fwrite writes binary representation of integer. fwrite写入整数的二进制表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM