0

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;

}

4

1 回答 1

0

您创建了一个clientData包含一个整数、两个字符串和一个双精度的结构。您以二进制模式打开文件,然后fwrite()将结构写入其中。

这意味着您正在以二进制形式写入整数和双精度,而不是字符串,因此您所看到的逻辑上是正确的,您可以使用 fread() 将文件读回结构,然后将其打印出来。

如果你想创建一个文本文件,你应该使用fprintf(). 您可以为整数和双精度值指定字段宽度,以便创建固定长度的记录(这对于随机访问至关重要)。

于 2015-06-07T23:04:41.513 回答