C - fread似乎没有将数据读回内存

时间:2014-06-19 05:18:18

标签: c structure binaryfiles fread

我有一个问题而且我不确定是什么原因造成的,因为我正在阅读的这本书并没有真正解释恐惧功能,甚至在阅读了这里的一些帖子之后我仍然无法想象发生了什么事。我认为这与将结构读回内存有关

问题在于,当它恢复阵列时,它仍然打印出空白,好像它没有恢复一样,但它声称整个10​​0个部分都已恢复。我倾倒它时只制作了3个结构部件,这可能是个问题吗?

结构有这种形式

    #define MAX_PARTS 100

    struct part {
        int number;
        char name[NAME_LEN+1];
        int on_hand;
    } inventory[MAX_PARTS];

这是函数

    void dump(void)
    {
        FILE *fp;
        const char *inv = "inventory.dat";
        int chk;

        if ((fp = fopen(inv, "wb")) == NULL) {
            fprintf(stderr, "Can't open file \"%s\"\n", *inv);
            exit(EXIT_FAILURE);
        }

        chk = fwrite(inventory, sizeof(struct part), MAX_PARTS, fp);
        if (feof(fp)) {
            fprintf(stderr, "End of file reached\n");
        } else if (ferror(fp)) {
            fprintf(stderr, "A write error occured\n");
        }
        fclose(fp);
        printf("File has Dumped %d of %d\n", chk, num_parts);
    }

    void restore(void)
    {
        FILE *fp;
        const char *inv = "inventory.dat";
        int chk;

        if ((fp = fopen(inv, "rb")) == NULL) {
            fprintf(stderr, "Can't open file \"%s\"\n", *inv);
            exit(EXIT_FAILURE);
        }

        chk = fread(inventory, sizeof(struct part), MAX_PARTS, fp);
        if (feof(fp)) {
            fprintf(stderr, "End of file reached\n");
        } else if (ferror(fp)) {
            fprintf(stderr, "A read error occurred\n");
        }
        fclose(fp);
        printf("File has restored %d parts\n", chk);
    }

其余代码:

    /* Maintains a parts database (array version) */

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

    #define NAME_LEN 25
    #define MAX_PARTS 100

    struct part {
        int number;
        char name[NAME_LEN+1];
        int on_hand;
    } inventory[MAX_PARTS];

    int num_parts = 0; /* number of parts currently stored */

    void dump(void);
    void restore(void);
    int find_part(int number);
    void insert(void);
    void search(void);
    void update(void);
    void print(void);

    /**********************************************************
     * main: Prompts the user to enter an operation code,     *
     *       then calls a function to perform the requested   *
     *       action. Repeats until the user enters the        *
     *       command 'q'. Prints an error message if the user *
     *       enters an illegal code.                          *
     **********************************************************/
     int main(void)
     {
         char code;

         for (;;) {
            printf("Enter operation code: ");
            scanf(" %c", &code);
            while (getchar() != '\n')   /* skips to end of file */
                ;
            switch (code) {
                case 'd': dump();
                          break;
                case 'r': restore();
                          break;
                case 'i': insert();
                          break;
                case 's': search();
                          break;
                case 'u': update();
                          break;
                case 'p': print();
                          break;
                case 'q': return 0;
                default: printf("Illegal code\n");
            }
            printf("\n");
         }
     }

    void dump(void)
    {
        FILE *fp;
        const char *inv = "inventory.dat";
        int chk;

        if ((fp = fopen(inv, "wb")) == NULL) {
            fprintf(stderr, "Can't open file \"%s\"\n", *inv);
            exit(EXIT_FAILURE);
        }

        chk = fwrite(inventory, sizeof(struct part), MAX_PARTS, fp);
        if (feof(fp)) {
            fprintf(stderr, "End of file reached\n");
        } else if (ferror(fp)) {
            fprintf(stderr, "A write error occured\n");
        }
        fclose(fp);
        printf("File has Dumped %d of %d\n", chk, num_parts);
    }

    void restore(void)
    {
        FILE *fp;
        const char *inv = "inventory.dat";
        int chk;

        if ((fp = fopen(inv, "rb")) == NULL) {
            fprintf(stderr, "Can't open file \"%s\"\n", *inv);
            exit(EXIT_FAILURE);
        }

        chk = fread(inventory, sizeof(struct part), MAX_PARTS, fp);
        if (feof(fp)) {
            fprintf(stderr, "End of file reached\n");
        } else if (ferror(fp)) {
            fprintf(stderr, "A read error occurred\n");
        }
        fclose(fp);
        printf("File has restored %d parts\n", chk);
    }

    /**********************************************************
     * find_part: Looks up a part number in the inventory     *
     *            array. Returns the array index if the part  *
     *            number is found, otherwise, returns -1.     *
     **********************************************************/
    int find_part(int number)
    {
        int i;

        for (i = 0; i < num_parts; i++)
            if (inventory[i].number == number)
                return i;
        return -1;
    }

    /**********************************************************
     * insert: Prompts the user for information about a new   *
     *         part and then inserts the part into the        *
     *         database. Prints an error message and returns  *
     *         prematurely if the part already exists or the  *
     *         database is full.                              *
     **********************************************************/
    void insert(void)
    {
        int part_number;

        if (num_parts == MAX_PARTS) {
            printf("Database is full; can't add more parts.\n");
            return;
        }

        printf("Enter part number: ");
        scanf("%d", &part_number);

        if (find_part(part_number) >= 0) {
            printf("Part already exists.\n");
            return;
        }

        inventory[num_parts].number = part_number;
        printf("Enter part name: ");
        read_line(inventory[num_parts].name, NAME_LEN);
        printf("Enter quantity on hand: ");
        scanf("%d", &inventory[num_parts].on_hand);
        num_parts++;
    }

    /**********************************************************
     * search: Prompts the user to enter a part number, then  *
     *         looks up the part in the database. If the part *
     *         exists, prints the name and quantity on hand;  *
     *         if not, prints an error message.               *
     **********************************************************/
    void search(void)
    {
        int i, number;

        printf("Enter part number: ");
        scanf("%d", &number);
        i = find_part(number);
        if (i >= 0) {
            printf("Part name: %s\n", inventory[i].name);
            printf("Quantity on hand: %d\n", inventory[i].on_hand);
        } else
            printf("Part not found.\n");
    }

    /**********************************************************
     * update: Prompts the user to enter a part number.       *
     *         Prints an error message if the part doesn't    *
     *         exist; otherwise, prompts the user to enter    *
     *         change in quantity on hand and updates the     *
     *         database.                                      *
     **********************************************************/
    void update(void)
    {
        int i, number, change;

        printf("Enter part number: ");
        scanf("%d", &number);
        i = find_part(number);
        if (i >= 0) {
            printf("Enter change in quantity on hand: ");
            scanf("%d", &change);
            inventory[i].on_hand += change;
        } else
            printf("Part not found.\n");
    }

    /**********************************************************
     * print: Prints a listing of all parts in the database,  *
     *        showing the part number, part name, and         *
     *        quantity on hand. Parts are printed in the      *
     *        order in which they were entered into the       *
     *        database.                                       *
     **********************************************************/
    void print(void)
    {
        int i;

        printf("Part Number   Part Name                "
               "Quantity on Hand\n");
        for (i = 0; i < num_parts; i++)
            printf("%7d       %-25s%11d\n", inventory[i].number,
                   inventory[i].name, inventory[i].on_hand);
    }

2 个答案:

答案 0 :(得分:1)

当你写MAX_PARTS时,它会读取那些记录。因此chk将是MAX_PARTS

它会给你任何你写的东西。如果您编写了有效的3条记录,那么它应该读取3条有效记录,其他记录将是垃圾记录。

答案 1 :(得分:1)

最基本的调试尝试会显示错误。只需将记录添加到print函数就可以解决问题。

还原时,不要更改num_parts。因此,当您要求打印时,它会打印零件。如果num_parts是您的程序所需数据的一部分,那么它也需要保存/恢复。或者,只写出已填充的部件数量,并将恢复功能中的num_parts设置为读取的部件数量。