C: Read and write a set of data to a file in binary mode (fread, fwrite)

Source: Internet
Author: User
Tags fread

  1. #include <stdio.h>
  2. #define SIZE 10
  3. struct student
  4. {
  5. Char name[10];
  6. int num;
  7. int age;
  8. Char addr[15];
  9. }stu[size];
  10. Save Data (fwrite)
  11. void Save ()
  12. {
  13. FILE *FP;
  14. fp = fopen ("Stu.dat", "WB");
  15. if (fp==null)
  16. {
  17. printf ("File can not open!\n");
  18. Return
  19. }
  20. for (int i=0;i<size;i++)
  21. {
  22. if (fwrite (&stu[i],sizeof (struct student), 1,FP)!=1)
  23. {
  24. printf ("File Write error!\n");
  25. }
  26. }
  27. Fclose (FP);
  28. }
  29. Read Data (fread)
  30. void Load ()
  31. {
  32. FILE *FP;
  33. fp = fopen ("Stu.dat", "RB");
  34. if (fp==null)
  35. {
  36. printf ("File can not open!\n");
  37. Return
  38. }
  39. for (int i=0;i<size;i++)
  40. {   
  41. if (fread (&stu[i],sizeof (struct student), 1,FP)!=1)
  42. {
  43. if (feof (FP))
  44. {
  45. Fclose (FP);
  46. Return
  47. }
  48. printf ("file read error!\n");
  49. }
  50. printf ("%-10s%4d%4d%-15s\n", stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
  51. }
  52. Fclose (FP);
  53. }
  54. int main ()
  55. {
  56. printf ("Please enter data of students:\n");
  57. for (int i=0;i<size;i++)
  58. {
  59. scanf ("%s%d%d%s", stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
  60. }
  61. Save ();
  62. Load ();
  63. return 0;
  64. }

C: Read and write a set of data to a file in binary mode (fread, fwrite)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.