-2

这是代码,

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>

struct num{
    int a[5];
};

int main(){
    struct num n;
    n.a[0]=56;

    FILE * fp=fopen("saman.txt","w+");

    if(fp==NULL){
        printf("error");
        exit(0);
    }

    fwrite(&n,sizeof(n),1,fp);  
    fread(&n,sizeof(n),1,fp);   
    printf("%i",n.a[0]);
}

输出是0,但应该是56,不是吗?你能帮帮我吗?

4

1 回答 1

4

当你写结构时,文件的位置指针会增加。当您尝试读取时,它会尝试从当前位置读取,但它现在位于文件末尾,因此您不会读取任何内容。

您应该检查 的返回值,fread看看它是否真的成功了。


在检查了 C 规范 (C11) 第 7.21.8.1 节(标题为“fread 函数”)之后,它实际上并没有说明出现错误时数据会发生什么,所以我会说你的数据状态尝试读入是未定义的,可以是任何东西。

于 2013-09-17T10:57:39.820 回答