首页 > 解决方案 > 程序从文件读取时显示随机列表数据

问题描述

我有一个家庭作业任务是创建一个包含旅行数据的链表并将数据写入二进制文件然后读取它。但是当我编写一个显示所有列表的函数时,它会显示我创建的列表,但也会显示随机数据.

我尝试过使用不同的循环,但由于某种原因 for 循环它不显示任何内容,只是崩溃。我是 C 的初学者,所以如果问题太愚蠢,我很抱歉......:D

typedef struct {
    char ID[20];
    char date[11];
    int duration;
    double price;
} excursion;

typedef struct Trip {
    excursion data;
    struct Trip *next;
} trip;


trip *head=NULL;
trip *current=NULL;


void displayALL()
{
        trip *temp;

        temp = head;
        while (temp != NULL) {
                printf("ID of Excursion is %s\nDuration is %d days\nDate of departure is %s\nThe price is %.2f\n",
                                temp->data.ID, temp->data.duration, temp->data.date, temp->data.price);
                temp = temp->next;
        }
}

我不会显示整个代码,因为另一部分工作我用这段代码编写列表:

FILE * fp;
trip *temp;

if ((fp = fopen("Excursion.bin", "wb")) == NULL) {
        printf("Error opening file");
        exit(1);
}

for (temp = head; temp != NULL; temp = temp->next) {
        if (fwrite(&temp->data, sizeof(excursion), 1, fp) != 1) {
                printf("Error in writing file\n");
                exit(0);
        }
}
fclose(fp);

并阅读这个:

FILE *fp;

if ((fp = fopen("Excursion.bin", "rb")) == NULL) {
        printf("No info added yet\n");
        exit(1);
}
while (1) {
        trip *temp = (trip*)malloc(sizeof(trip));
        if (head == NULL) {
                head = temp;
                current = head;
                current->next = NULL;
        } else {
                current->next = temp;
                current=temp;
                current->next = NULL;
        }
        if (fread(&temp->data, sizeof(excursion), 1, fp) != 1) {
                break;
                printf("Error reading file\n");
                exit(0);
        }
}
fclose(fp);

这是它显示的随机数据: 游览的 ID 是 └ 持续时间是 0 天 出发日期是 价格是 0.00 游览的 ID 是И#▌ 持续时间是 -202182160 天 出发日期是фхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■а5 ▐ 价格为-1.#R

标签: clistbinaryfiles

解决方案


你的主要问题就在这里。

if(fread(&temp->data, sizeof(excursion), 1, fp) != 1)

和这里

if(fwrite(&temp->data,sizeof(excursion), 1, fp) != 1)

因此,您似乎正在尝试将整个结构写入文件并读取整个结构,但由于某种原因,您告诉它将其放入数据中,或将其从数据中取出。数据不是整个结构,而是结构内部的 11 字节字符数组。

做这个。

if(fread(temp, sizeof(excursion), 1, fp) != 1)

 if(fwrite(temp,sizeof(excursion), 1, fp) != 1)

推荐阅读