使用fwrite()将队列结构中的结构写入二进制文件

时间:2017-05-25 19:07:16

标签: c data-structures file-handling fwrite

我想使用fwrite()将队列(数据结构)struct中的结构写入二进制文件。

struct addressbook
{
    char first[15];
    char surname[15];
    char address[60];
    char city[15];
    char country[15];
    char zip[6];
    char phone[15];
    char mob[15];
};

struct node
{
    struct addressbook data;
    struct node *next;
};

struct node *front = NULL;
struct node *rear = NULL;

我的代码如下:

void writedata (void)
{
    FILE *fp;

    char CONTINUE;

    struct addressbook blank;
    struct node *temp;

    fp = fopen("asdf.dat","ab");

    while(1)
    {
        temp = (struct node*)malloc(sizeof(struct node));

        if (temp != NULL)
        {
            fflush(stdin);
            printf("\nEnter First name?\n");
            gets(temp->data.first);

            printf("Enter Surname?\n");
            gets(temp->data.surname);

            printf("Enter Street Address (with commas)?\n");
            gets(temp->data.address);

            printf("Enter City?\n");
            gets(temp->data.city);

            printf("Enter Country?\n");
            gets(temp->data.country);

            printf("Enter Zipcode?\n");
            gets(temp->data.zip);

            printf("Enter Phone number?\n");
            gets(temp->data.phone);

            printf("Enter Mobile number?\n");
            gets(temp->data.mob);

            temp->next = NULL;

            fwrite(&temp->data,sizeof(struct addressbook),1,fp);

            if (front == NULL)
            {
                front = temp;
            }

            else
            {
                rear->next = temp;
            }

            rear = temp;

        }

        else
        {
            printf( "No memory available.\n");
        }

        printf("CONTINUE\nY-YES \nN-NO\n? ");
        fflush(stdin);
        CONTINUE = getchar();

        if (CONTINUE == 'N' || CONTINUE == 'n')
            break;
    }

    fclose(fp);
}

我在输出处获得垃圾值。

0 个答案:

没有答案