This is a code to the data in inputfile to a new file and if an output file already exists the user will have option to either provide new address or exit.
when I place the goto readout
inside switch, the switch and goto work but after that program exits without taking the output file address.
This is the screenshot:
And the code:
#include<stdio.h>
int main()
{
int n;
FILE *in,*out;
char inadd[50],outadd[50],ch;
readin:
printf("Enter the address of input file: ");
gets(inadd);
in=fopen(inadd,"r");
if(in==NULL) //reading and validating input file address
{
printf("There is an error with the opening of the file, please reenter the file name.\n");
goto readin; //readin call
}
readout:
printf("Enter the address of output file: ");
gets(outadd);
out=fopen(outadd,"r");
if(out!=NULL) //reading and validating output file address
{
printf("File already exists, to reenter file address enter 1 & to exit enter 2:");
scanf("%d",&n);
switch (n) //switc-case
{
case 1: printf("\n");
goto readout; //readout call
break;
case 2: exit(0);
}
}else //file is read and copied to input file.
{
out=fopen(outadd,"w");
while(!feof(in))
{
fscanf(in,"%c",&ch);
fprintf(out,"%c",ch);
}
fclose(in);
fclose(out);
printf("\n\nSuccess!\nFile copied successfully\n\n");
}
}
Try this code below. The reason being is that scanf leave newline in your buffer and gets
pick that up.
printf("File already exists, to reenter file address enter 1 & to exit enter 2:");
scanf("%d",&n);
int c;
do {
c = getchar();
}while(c != '\n' && c != EOF);