Program for writing to and from a file

#include
#include
#include

void main()
{
FILE *fp;
char *str;
int i;
int flag;
char temp[2];
clrscr();

printf("\n\n\n\t\t\t Program for writing to and from a file");

fp=fopen("test.txt","w");

if(fp!=NULL)
printf("\n\n\t\t\t File opened properly...");
else
{
printf("\n\n\t\t\t Error : Unable to open file...");
return 1;
}

printf("\n\n\t\t\t Enter few line of text ('end' to finish )");
printf("\n\n\t >> ");

while(1)
{
fflush(stdin);
gets(str);
fputs(str,fp);

fputs("\n",fp);
if(strcmpi(str,"end")==0)
break;
printf("\t ");


}


flag=fclose(fp);

if(flag==-1)
{
printf("\n\n\t\t\t Error : File was not closed properly...");
exit();
}
else
printf("\n\n\t\t\t File was closed properly...");

printf("\n\n\n\t\t\t Now opening for reading...");
//delay(1500);


fp=fopen("test.txt","r");

if(fp!=NULL)
printf("\n\n\t\t\t File opened properly...");
else
{
printf("\n\n\t\t\t Error : Unable to open file...");
exit();
}

printf("\n\n\n\t >> ");

while(fgets(str,75,fp)!=NULL)
{
i=0;
while(i<3)
{
temp[i]=str[i];
i++;
}

if(strcmpi(temp,"end")==0)
break;

printf("%s",str);
printf("\t ");

}

flag=fclose(fp);

if(flag==-1)
{
printf("\n\n\t\t\t Error : File was not closed properly...");
exit();
}

else
printf("\n\n\t\t\t File was closed properly...");


getch();

}

No comments:

Post a Comment