简体   繁体   English

c程序读写文本文件

[英]c program to read & write text file

Below is a quick program I created, The program is suppose to keep a trace of blood donors. 下面是我创建的一个快速程序,该程序假设留下一丝献血者。

#include <stdio.h>
#include <conio.h>

struct donors
{
 char name[20];
 char address[40];
 int age;
 int blood_type;
};

void main()
{
  int ask,i=0;
  struct donors d;

  FILE *fp;
  fp = fopen("Blood_Donors.txt","r");


  clrscr();

  if(fp==NULL)
  {
    printf("Error: Unable to open file.");
    printf("\nDo you want to create a new file ? (Y = 1 / N = 0) : ");
    scanf("%d",&ask);
    if(ask==1)
    {
      fp = fopen("Blood_Donors.txt","w");
    }

    if(fp!=NULL)
    {
      printf("\nFile Created\n");
    }
    else
    {
     if(ask==1)
     {
      printf("\nError: Unable to create file");
      printf("\nPress any key to exit the program");
      getch();
      exit(1);
      }
      else
      {
       printf("\nFile not created \nPress any key to exit the program");
       getch();
       exit(1);
      }
    }
  }
  else
  {
   fp = fopen("Blood_Donors.txt","a");
   printf("Do you want to enter a record ? (Y = 1 / N = 0) : ");
   scanf("%d",&ask);
  }

  while(ask==1)
  {
    i=i+1;
    fflush(stdin);
    printf("Enter name (Maximum 20 characters) : ");
    gets(d.name);

    fflush(stdin);
    printf("Enter address (Maximum 40 characters) : ");
    gets(d.address);

    fflush(stdin);
    printf("Enter age (Maximum 2 characters) : ");
    scanf("%d",&d.age);

    fflush(stdin);
    printf("Enter Blood Type \n(A- = 1, A+ = 2, B- = 3, B+ = 4, AB- = 5, AB+ = 6, O- = 7, O+ = 8) : ");
    scanf("%d",&d.blood_type);

    fprintf(fp,"<donor %d>\nName: %s\nAddress: %s\nAge: %d\nType: %d\n\n",i, d.name, d.address, d.age, d.blood_type);
    fflush(stdin);

    printf("\n\nDo you want to enter another record ? (Y = 1 / N = 0) : ");
    scanf("%d",&ask);
   }

  fclose(fp);
  getch();
}

a) how to increase the value of i appropriately ? a)如何适当增加i的价值? where i holds the number of the previous donor. 我持有前一个捐赠者的人数。 b) how to print the details of all donors below age 30 and whose name starts with 's' ? b)如何打印30岁以下且名字以“s”开头的所有捐赠者的详细信息?

a)Since you are saving to a file, why not declare the first line of the file as a single number i representing the number of donors so far, followed by i lines of donors? a)由于您要保存到文件,为什么不将文件的第一行声明为单个数字i代表到目前为止的捐赠者数量,然后是i行捐赠者?

b)you might want to lookup xml's b)你可能想要查找xml

您可以将这些用户存储在数据结构中,例如LinkedList,然后遍历链接列表以查找名称以“s”开头的所有用户,您也可以对这些项目进行计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM