use fseek with structure array in c

穿精又带淫゛_ 提交于 2019-12-25 05:04:03

问题


everyone.so I have this binary file with data written to it using an array of structures. Now I want to update a specific record in it. however, i am unsure of how to achieve this based on using fseek. Could anyone please offer some assistance?

struct clientData{
    char cliName[16];
    char persIdNum[10];
    int pos;
    char empID[6];

};


     FILE* fptr;
    //FILE* f;
    char compName[15];
    printf("Enter company name: ");
    scanf(" %s", compName);
    fptr = fopen(strcat(compName,".dat"), "wb");

    struct clientData data[5];

    int i;

   for(i=0; i<5; i++){

            data[i].pos = i;
            printf("\nEnter client name %d: ", i+1);
            scanf(" %s", data[i].cliName);

            printf("\nEnter client personal id %d: ", i+1);
            scanf(" %s", data[i].persIdNum);

            printf("\nEnter employee ID %d: ", i+1);
            scanf(" %s", data[i].empID);
}

    fwrite(data, sizeof(struct clientData), 5, fptr);
    fclose(fptr);
///////////////////////////////////////////////////////////////////////////////////////////////////////

FILE *fptr;
struct clientData info[5];

fptr = fopen(CmpName, "rb+");

        if (fptr == NULL)
            printf("eRROR OPENING");
     do {
       system("cls");
    printf("\n\t\t\t   CLIENTS IN FILE: %s ", CmpName);
     for(i=0; i<5; i++){
        fread(info, sizeof(struct clientData), 5, fptr);
        printf("\n\n\t\t\t\t%d  %s", info[i].pos+1, info[i].cliName);
     }

    printf("\n\t\t******************************************************");

    printf("\n\n\t\t\tSelect client name to be updated: ");
    scanf(" %d", &CliName);
        if(CliName >=1 && CliName <=5 ){

            correct = true;
            for(i=0; i<5; i++){
                fread(info, sizeof(struct clientData), 5, fptr);

/*i want to fseek to the positon of the data selected above by the user.
where should i put it?*/

                         printf("\n\n\t\t\tEnter New Client Name:");;
                         scanf(" %s", NewCliName);

                         printf("\n\n\t\t\tEnter New Client Personal ID:");;
                         scanf(" %s", NewCliPersID);

                         strcpy(info[i].cliName, NewCliName);
                         strcpy(info[i].persIdNum, NewCliPersID);

                         fwrite(info, sizeof(struct clientData), 5, fptr);
                         break;
                         }//END OF FOR LOOP

回答1:


Use

fseek(fptr,sizeof(struct clientData)*(CliName-1),SEEK_SET)


来源:https://stackoverflow.com/questions/43638864/use-fseek-with-structure-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!