二进制文件写/读问题

时间:2010-05-16 22:45:57

标签: c file binary

好的,我的代码读取二进制文件有问题......

首先我会告诉你我的写作代码:

void book_saving(char *file_name, struct BOOK *current)
{
    FILE *out;
    BOOK buf;

    out = fopen(file_name, "wb");

    if(out != NULL)
    {
        printf_s("Writting to file...");
        do
        {
            if(current != NULL)
            {
                strcpy(buf.catalog_number, current->catalog_number);
                strcpy(buf.author, current->author);
                buf.price = current->price;
                strcpy(buf.publisher, current->publisher);
                strcpy(buf.title, current->title);
                buf.price = current->year_published;
                fwrite(&buf, sizeof(BOOK), 1, out);
            }
            current = current->next;
        } while(current != NULL);

        printf_s("Done!\n");
        fclose(out);
    }
}

这是我阅读的“版本”:

int book_open(struct BOOK *current, char *file_name)
{
    FILE *in;
    BOOK buf;
    BOOK *vnext;
    int count;
    int i;

    in = fopen("west", "rb");
    printf_s("Reading database from %s...", file_name);
    if(!in)
    {
        printf_s("\nERROR!");
        return 1;
    }

    i = fread(&buf,sizeof(BOOK), 1, in);
    while(!feof(in))
    {
        if(current != NULL)
        {
            current = malloc(sizeof(BOOK));
            current->next = NULL;
        }

        strcpy(current->catalog_number, buf.catalog_number);
        strcpy(current->title, buf.title);
        strcpy(current->publisher, buf.publisher);
        current->price = buf.price;
        current->year_published = buf.year_published;
        fread(&buf, 1, sizeof(BOOK), in);

        while(current->next != NULL)
            current = current->next;

        fclose(in);

    }
    printf_s("Done!");

    return 0;
}

我只需要将我的链表保存在二进制文件中并能够将其读回来......请帮助我。程序只是在每次不同的情况下都不会读它或崩溃......

2 个答案:

答案 0 :(得分:2)

  1. 您的do..while循环可以更好地形成。如果你要在最后检查,也不要在开头检查。如果您发现必须这样做,则可能没有使用正确的流量控制。例如,您应该在这里说while(current != NULL) { }

  2. 你想用if(current != NULL) { }做什么?您正在将循环中的当前节点设置为全新的BOOK,并创建其下一个元素NULL。为什么?为什么不直接镜像你在写作方法中的循环呢?

  3. 如果隐含current == NULL,请查看您在做什么 - 您正在strcpy阅读方法。不要那样做。

  4. 您似乎在fclose(in)的{​​{1}}循环中说while

  5. 编译后我会得到更多。


    好的,我编写的代码有点做了2个假设

    1. 这不是作业问题
    2. book_open只有1个指针(BOOK),其他一切都是分配了内存的数组
    3. book_saving - 简单地循环和写入

      next

      book_open - 指向指向FILE *out; BOOK buf; out = fopen(file_name, "wb"); if(out == NULL) return; printf_s("Writing to file..."); while(current != NULL) { fwrite(&buf, sizeof(BOOK), 1, out); current = current->next; } printf_s("Done!\n"); fclose(out); 的指针

      BOOK

      我认为那更好。

答案 1 :(得分:0)

看起来您可能正在尝试传入一个已填充的现有列表,或者如果没有传入,则read函数会尝试分配并创建一个列表。这两种情况看起来都不对。

如果它是第一个(传入现有列表),则while(current->next != NULL)循环将扫描到它的末尾。如果您正在尝试创建新列表,那么看起来需要做一些额外的工作来将新节点链接在一起。