0

I am new here so sorry for any misunderstanding. I am learning Random Access File on C Language. And I am confused about the variable blankClient. It is not an array, but how could Deitel (the author) initialize 100 blanks record using blank Client. I though it should be like: struct clientdata blankClient[100];

/*Creating a random-access file sequentially */
#include <stdio.h>

struct clientdata {
  int acctNum;          /*account number*/
  char lastname[15];    /*account last name*/
  char firstname[10];   /*account first name */
  double balance;       /*account balance*/
};

int main (void){

int i;  /*counter used to count from 1-100 */

/*create clientData with default info */
struct clientdata blankClient = {0, "","", 0.0};

FILE *cfPtr; /*credit.dat file pointer */

if ((cfPtr =fopen("credit.dat", "wb")) == NULL) {
    printf("File could not be opened. \n");
}
/*output 100 blank records to file */
else {
        for (i=1; i<=100; i++) {
            fwrite(&blankClient, sizeof( struct clientdata), 1, cfPtr);
        }
        fclose (cfPtr);
    }
return 0;
}
Khoily
  • 17
  • 3
  • Check how fwrite() works: http://www.cplusplus.com/reference/cstdio/fwrite/ You are not actually writing 100 times in blankClient but in cfPtr – smagnan May 26 '14 at 20:56
  • You probably do not want to use a `double` for currency. Comparisons with, for example 0.1 units, are not exact. – wallyk May 26 '14 at 20:57
  • _Internally, the function interprets the block pointed by ptr as if it was an array of (size*count) elements of type unsigned char, and writes them sequentially to stream as if fputc was called for each byte_ I got the answer, thanks @smagnan – Khoily May 26 '14 at 21:13
  • @Khoily No problem (: When you have a doubt about how a function really work, don't hesitate to check. – smagnan May 26 '14 at 21:15

1 Answers1

1

The code is writing out the same source record 100 times. This is similar to how you can make a hundred clapping sounds with only two hands.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • So how does it store the information? I mean, does it overwrite itself like you reinitialize a variable? – Khoily May 26 '14 at 20:56
  • @Khoily: No, when you write to a file, the output cursor advances and you keep writing more and more data (unless you seek back explicitly). It's just like when you print text to the screen: Each character goes *after* the previous one, you don't manually have to advance the cursor. – Kerrek SB May 26 '14 at 20:57
  • @KerretSB, so you mean the variable store 100 pieces of information into the same byte? – Khoily May 26 '14 at 21:02
  • @Khoily: No, there's just one variable, just like you have only one pair of hands. But you write it to the file a hundred times (just like you can clap a hundred times). – Kerrek SB May 26 '14 at 21:04