如何使用C语言编程读取和写入数据

问题描述 投票:0回答:1
 #include <stdio.h>


#include <stdlib.h>

struct customer {
   char  fname[20],lname[20];
   int   acct_num;
  float acct_balance;
};

void main ()
{
    FILE *outfile;
  struct customer input;

  // open Accounts file for writing
  outfile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","w");
   if (outfile == NULL)
     {
     fprintf(stderr, "\nError opening accounts.dat\n\n");
      exit (1);
    }

  // instructions to user
   printf("Enter \"stop\" for First Name to end program.");

  // endlessly read from keyboard and write to file
   while (1)
    {
     // prompt user
      printf("\nFirst Name: ");
     scanf ("%s", input.fname);
     // exit if no name provided
      if (strcmp(input.fname, "stop") == 0)
        exit(1);
     // continue reading from keyboard
      printf("Last Name : ");
     scanf ("%s", input.lname);
      printf("Acct Num  : ");
      scanf ("%d", &input.acct_num);
      printf("Balance   : ");
      scanf ("%f", &input.acct_balance);

      // write entire structure to Accounts file
      fwrite (&input, sizeof(struct customer), 1, outfile);
    }
   FILE *infile;
   /*** open the accounts file ***/
   infile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","r");
   if (infile == NULL)
     {
     fprintf(stderr, "\nError opening accounts.dat\n\n");
      exit (1);
     }

  while (fread (&input, sizeof(struct customer), 1, infile))
      printf ("Name = %10s %10s   Acct Num = %8d   Balance = %8.2f\n",
              input.fname, input.lname, input.acct_num, input.acct_balance);

 }

当我在程序中输入信息时,它只是在文件.dat中写入随机字符,而不显示我已编写的信息。请帮助我找到问题所在。

c record
1个回答
1
投票

您有:

© www.soinside.com 2019 - 2024. All rights reserved.