下面是我创建的一个快速程序,该程序应该保留献血者的踪迹。
#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) 如何适当增大i的值?其中 i 持有前一个捐赠者的号码。 b) 如何打印所有30岁以下且名字以's'开头的捐赠者的详细信息?
最佳答案
a) 既然您要保存到文件,为什么不将文件的第一行声明为单个数字 i 表示到目前为止的捐赠者数量,后面是 i 行捐赠者?
b)您可能想要查找 xml
关于C程序读写文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7758361/