在c中使用带有结构数组的fseek

时间:2017-04-26 15:43:53

标签: c fseek

everyone.so我有这个二进制文件,其中使用结构数组写入数据。现在我想更新其中的特定记录。但是,我不确定如何使用fseek实现这一点。有人可以提供一些帮助吗?

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 个答案:

答案 0 :(得分:0)

使用

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