This is the base code for the program I am writing to use C files. I am trying to determine if the output file exists and whether it exists. I want to ask the user if they want to overwrite it or not. It is for this reason that I first opened the outfilename file with fopen (outfilename, "r"); unlike fopen (outfilename, "w");
It discovers that the file does not exist, however, if it exists, it executes printf ("The output file already exists, overwrites (y / n):"); but completely ignores scanf ("% c", & yn); expression!
printf at the end of the program reads "yn = 0" if the file does not exist and simply "yn =" if it exists. Can anybody help me?
#include <stdio.h> #include <stdlib.h> #include <float.h> #include <string.h> int main(void) { FILE *inf; FILE *outf; char filename[21],outfilename[21]; char yn='0'; printf("Please enter an input filename: "); scanf("%s",&filename); printf("Please enter an output filename: "); scanf("%s",&outfilename); /* Open file for reading */ inf=fopen (filename,"r"); outf=fopen(outfilename,"r"); /*check that input file exists*/ if (inf!=NULL) { /*check that the output file doesn't already exist*/ if (outf==NULL){ fclose(outf); /*if it doesn't already exist create file by opening in "write" mode*/ outf=fopen(outfilename,"w"); } else { /*If the file does exist, give the option to overwrite or not*/ printf("Output file already exists, overwrite (y/n):"); scanf("%c",&yn); } } printf("\n yn=%c \n",yn); return 0; }
source share