Here is the modified code. Added gets
instead of scanf
and added return 0;
if file is not opened.
#include <stdio.h>
int main()
{
char string[100];
char filename[20];
int n=0;
FILE *fp;
printf(" Enter the name of file to open ");
gets(filename);
fp =fopen(filename,"wr");
if(fp==NULL)
{
printf("unable to open File");
return 0; // do not proceed
}
for(n=1;n<6;n++)
{
printf("\nEnter line %d:",n);
gets(string);
fputs(string,fp);
fputs("\n",fp);
}
fclose(fp); /*close the file*/
fp =fopen(filename,"r");
if(fp==NULL)
{
printf("unable to open File");
return 0; // do not proceed
}
for(n=1;n<6;n++)
{
fgets(string,100,fp);
printf("%s",string);
}
fclose(fp); // close after reading.
return 0;
}