これは、C でファイルを使用して練習するために書いているプログラムの基本的なコードです。出力ファイルが既に存在するかどうかを検出しようとしています。存在する場合は、ユーザーに上書きするかどうかを尋ねたいと思います。これが、最初に outfilename ファイルを fopen(outfilename,"r"); で開いた理由です。fopen(outfilename,"w"); とは対照的です。
ファイルが存在しない場合を検出しますが、存在する場合は printf("Output file already exists, overwrite (y/n):"); を実行します。ステートメントですが、scanf("%c",&yn); を完全に無視します。声明!
プログラムの最後のprintfは、ファイルが存在しない場合は「yn = 0」を読み取り、存在する場合は単に「yn =」を読み取ります。誰でも私を助けることができますか?
#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;
}