×

Friday, August 14, 2009

C Tutorial: example of write, read & remove

#include....

void main()
{
FILE *file;
char name[15];
int age;
char addr[15];
int s;
b:
clrscr();
printf("Select your choice:");
printf("\n%s\n%s\n%s\n%s\n%s","1- Write",
"2- Read",
"3- Remove",
"4- Exit",
"Choice: ");
scanf("%d",&s);
switch(s)
{
case 1: {
printf("Enter Name: ");
fflush(stdin);gets(name);
printf("Enter Age: ");
scanf("%d",&age);
printf("Enter Address: ");
fflush(stdin);gets(addr);

file=fopen("contact.dat","a+");
fprintf(file,"%s %d %s\n",name,age,addr);
fclose(file);
}
break;
case 2: {
file=fopen("contact.dat","r");
if(file==NULL)
printf("Error: couldn't read file.");
else
{
printf("%-13s %-13s %s","Name","Age","Address");
while(!feof(file))
{
fscanf(file,"%s %d %s",&name,&age,&addr);
if(feof(file))
{ \
break;
}
printf("\n%-13s %-13d %s",name,age,addr);
}
fclose(file);
}
getch();
}
break;
case 3: {

if(remove("contact.dat")==-1)
perror("Error deleting file.");
else
{
remove("contact.dat");
printf("File successfully removed.");
}
getch();
}
break;
case 4: exit(1);break;
default: printf("Press any key to continue.");getch();
}
goto b;
}

No comments: