写入文件的结构数据未正确读取

时间:2014-10-17 10:20:37

标签: c

printItems()始终打印第一个输入的项目。当我选择更新项目详细信息时,它们已在文件中更新,但printItems()未显示更新的项目。

struct canteen
{
    char itemId[15];
    char name[15];
    int price;

};



void printItems()
{
    FILE *fp1;
    fp1=fopen("items.txt","r");
    struct canteen c;
    printf("\t%-15s%-30s%-5s\n","Item Id","Item Name","Price");

    while(fread(&c,sizeof(struct canteen),1,fp1)!=NULL)
    {
        printf("\t%-15s%-30s%-5d\n",c.itemId,c.name,c.price);
    }
    fclose(fp1);
}

int updateItem(char id[])
{
    FILE *fp;
    int pos=0;
    fp=fopen("items.bin","r+");
    int found=0;
    struct canteen b;
    while(fread(&b,sizeof(struct canteen),1,fp)!=NULL)
    {
            pos=ftell(fp);
            if(strcmp(b.itemId,id)==0)
            {
                found=1;
                fseek(fp,-sizeof(struct canteen),1);
                printf("Enter new Item ID: ");
                scanf("%s",b.itemId);
                printf("Enter new Item Name: ");
                scanf("%s",b.name);
                printf("Enter New Item price : ");
                scanf("%d",&b.price);
                fwrite(&b,sizeof(struct canteen),1,fp);
                fclose(fp);
                break;

            }
    }

    fclose(fp);
    if(found==1)
    return 1;
    else
    {
    return 0;

    }

}



void main()
{

    FILE *fp1;
    FILE *fp2;
    char s[1];
    char choice[1];
    char id[15];

    int n,i,j;
    printf("Enter number of Items\n");
    scanf("%d",&n);
    fp1=fopen("items.bin","w");
    struct canteen c;
    for(i=0;i<n;i++)
    {
        printf("Enter item %d id : ",i+1);
        scanf("%s",c.itemId);
        printf("Enter item %d name : ",i+1);
        scanf("%s",c.name);
        printf("Enter item %d price : ",i+1);
        scanf("%d",&c.price);
        fwrite(&c,sizeof(struct canteen), 1, fp1);
    }

    fclose(fp1);
    printf("Item details are stored into file items.txt\n");

    printItems();

    while(1)
    {
    printf("Do you want to update items?\n Enter y or n : ");
    scanf("%s",s);
    if(s[0]!='n')
    {
        printf("Enter Item Id: ");
        scanf("%s",id);
        if(!updateItem(id))
            printf("No item found with id: %s",id);
        else
        {
            printf("Item detials after updation.\n");
            printItems();
        }

    }
    else
        break;
    }

 getch();
}

printItems()始终打印第一个输入的项目。当我选择更新项目详细信息时,它们已在文件中更新,但printItems()未显示更新的项目。

0 个答案:

没有答案