【问题标题】:How to solve this problem with files in C?如何用C中的文件解决这个问题?
【发布时间】:2026-01-02 13:45:01
【问题描述】:

由于某种原因,函数loadPerson 总是返回0 作为输出。

我认为问题与结构PERSON 中的变量分数有关,但我不知道问题是什么。比如不知道保存函数会保存分数的值还是地址的值(因为是指针)。

你能帮我找出问题吗?

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

#define N 3

typedef struct person{
    int age;
    float *scores;
} PERSON;

int savePerson(PERSON person, char *fileName){
    FILE *file;
    int result = 0;
    file = fopen(fileName,"wb");
    if (file){
        if(fwrite(&person,sizeof(PERSON),1,file)>0){
            result = 1;
        }
    }
    return result;
}

int loadPerson(PERSON *person, char *fileName){
    FILE *file;
    int result = 0;
    file = fopen(fileName,"rb");
    if (file){
        if(fread(person,sizeof(PERSON),1,file)>0){
            result = 1;
        }
    }
}

int main()
{
    char fileName[15] = "file1.bin";
    float scores[3] = {2.0,8.0,9.0};
    PERSON p1,p2;
    int i;

    p1.age = 35;
    p1.scores = scores;
    printf("Salvando\n");
    if(savePerson(p1,fileName)){
        printf("Saving OK!\n");
    }
    else{
        printf("Saving BAD!\n");
    }

    if(loadPerson(&p2,fileName)){
        printf("Loading OK!");
        printf("AGE: %d\n",p2.age);
        printf("SCORES:\n");
        for(i=0;i<N;i++){
            printf("%f,",p2.scores[i]);
        }
        printf("\n");
    }
    else{
        printf("Loading BAD!");
    }
    return 0;
}       

【问题讨论】:

  • 请定义“无法正常工作”。程序崩溃了吗?是不是让你家着火了?它是否输出了超出您预期的内容,如果是,请详细说明
  • 我猜它不会总是返回 0。
  • 请对您的问题提供更详细的说明。 is not working proper 之类的表达式无助于找出问题所在。您应该说明您的预期输出是什么,实际输出是什么以及为什么说实际输出是错误的。

标签: c file io


【解决方案1】:

看函数原型:int loadPerson(PERSON *person, char *fileName) 你忘了在函数结束时return result;

同样,一旦解决了这个问题,您在尝试将数组写入文件时也会遇到问题。您可能希望将结构更新为以下内容:

typedef struct person{
    int age;
    float scores[N];
} PERSON;

【讨论】:

  • 为什么要这样使用结构?
  • 因为此时结构中包含一个指针。所以你将分数的地址写入文件,而不是分数。
【解决方案2】:

失败与数据结构的内容无关。此功能失败的方式很少。以下版本将让您弄清楚是哪种情况。

int loadPerson(PERSON *person, char *fileName){
    FILE *file;
    int result = 0;
    file = fopen(fileName,"rb");
    if (file){
        if(fread(person,sizeof(PERSON),1,file)>0){
            result = 1;
        }else{
            printf("File read error!");
        }
    }else{
        printf("File not found: %s", fileName);
    }
    return result;
}

您尝试打开的文件不存在,或者它包含的数据不足以让您读取一个结构。无论哪种情况,都会打印一条错误消息。

(“找不到文件”很可能是因为该文件位于一个目录中,并且您的程序正在使用不同的 当前目录 设置执行。您需要查看您的开发环境来修复成功打开文件后立即出现“文件读取错误”可能意味着您尝试读取的文件不包含足够的字节来读取 PERSON 结构。您应该得到如果它读取了一项,则从fread 返回值1。检查文件的大小。)

当然,如果函数确实成功了,调用代码仍然需要知道这一点。即使函数被声明为返回int,您的代码也没有返回值。我冒昧地返回了您明确打算用于此目的的值。我建议你仔细看看为什么你的编译器没有警告你这个严重的问题......或者如果有,你为什么忽略它。

【讨论】:

    最近更新 更多