Search code examples
notepadrandomaccessfilemissing-symbols

Weird looking symbols in dat file?


Learning to program in C. Used a textbook to learn about writing data randomly to a random access file. It seems like the textbook code works ok. However the output in the Notepad file is: Jones Errol Ÿru ”#e©A Jones Raphael Ÿru €€“Ü´A. This can't be correct yeah? Do you know why the numbers don't show?

I have no idea how to format code properly. Always someone tells me it is bad. I use CTRL +K. And in my compiler follow the book exactly. I'm sorry if it isn't correct. Maybe you can tell me how? Thanks Here is the code:

#include <stdio.h>
//clientData structure definition
struct clientData{
       int acctNum;
       char lastName[15];
       char firstName[10];
       double balance;
       };

int main (void){
    FILE *cfPtr;//credit.dat file pointer
    //create clientData with default information
    struct clientData client={0,"","",0.0};
    if ((cfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\clients4.dat","rb+"))==NULL){
         printf("The file could not be opened\n");
    } 
    else {
       //require user to specify account number
       printf("Enter account number"
              "(1 to 100, 0 to end input)\n");
       scanf("%d",&client.acctNum);

       // users enters information which is copied into file
       while (client.acctNum!=0) {
                                                                                    //user enters lastname,firstname and balance
            printf("Enter lastname,firstname, balance\n");

            //set record lastName,firstname and balance value
            fscanf(stdin,"%s%s%lf", client.lastName,
                   client.firstName, &client.balance);

            //seek position in file to user specified record
            fseek(cfPtr,
                  (client.acctNum-1)* sizeof (struct clientData),
                  SEEK_SET);

            //write user specified information in file
            fwrite(&client,sizeof(struct clientData),1,cfPtr);

            //enable user to input another account number
            printf("Enter account number\n");
            scanf("%d",&client.acctNum);
       }
       fclose(cfPtr);
   return 0;

}


Solution

  • You have created a structure clientData which contains an integer, two strings and a double. You open the file in binary mode and you use fwrite() to write the structure to it.

    This means you are writing the integer and the double in binary, and not as character strings, so what you see is logically correct, and you could read the file back into a structure with fread() and then print it out.

    If you want to create a text file, you should use fprintf(). You can specify the field widths for integer and double values, so you can create a fixed-length record (which is essential for random access).