are structs like block arrays?

Discussion in 'OT Technology' started by lilmonkee, Apr 30, 2004.

  1. lilmonkee

    lilmonkee Resident Pharm.D. :)

    Joined:
    Jun 1, 2000
    Messages:
    4,310
    Likes Received:
    0
    Location:
    Houston, Texas
    this is for my c programming class. I'm having problems determining how this code works :


    using a struct clientData{
    int acctNum;
    char lastName[15];
    char firstName[10];
    float balance;
    };

    Code:


    while (client.acctNum!=0) {
    printf("Enter lastname, firstname, balance\n? ");
    scanf("%s%s%f", &client.lastName, &client.firstName, &client.balance);
    fseek(cfPtr, (client.acctNum-1) *sizeof(struct clientData), SEEK_SET);
    fwrite(&client,sizeof(struct clientData),1,cfPtr);
    printf"Enter account number\n?");
    scanf("%d", &client.acctNum);


    i'm confused on what exactly client.acctNum-1 is actually doing. I know SEEK_SET starts at the beginning of a file and fseek puts the pointer at that position, but client.acctNum-1 *sizeof.. ?

    is it like an array where it starts off at a structarray [1] and client.acctNum-1 writes it in structarray [2]? and if so, how is it incremented for the next set of client's last name, first name and balance info?
     
  2. TMReX

    TMReX Spoooooon!

    Joined:
    May 23, 2003
    Messages:
    50
    Likes Received:
    0
    Location:
    you better check under the sea! or Dallas
    Assuming 1 byte for char, 4 bytes for int, and 4 bytes for float, you get a total of 33 bytes used by the struct. So account 1 starts at byte 0 of the file ((1 - 1) * 33), account 2 at byte 33 ((2 - 1) * 33), account 11 at byte 330 ((11 - 1) * 33), etc. Nice and easy to read the accounts back out, just move to the proper offset and read in 33 bytes into the struct. Just don't change the struct between writing and reading. ;-)
     
  3. lilmonkee

    lilmonkee Resident Pharm.D. :)

    Joined:
    Jun 1, 2000
    Messages:
    4,310
    Likes Received:
    0
    Location:
    Houston, Texas
    thank you ! :)
     

Share This Page