下面是问题的主要描述,它发生在哪里。但简单地说,我无法弄清楚为什么在询问后会收到错误消息
if (outf!=NULL){
printf("Output file already exists, overwrite (y/n):");
scanf("%c",yn);
}
其中 outf 是指向现有文件的文件指针。请在代码中途阅读描述。
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <string.h>
int main() {
/* Declare file pointer */
FILE *inf;
FILE *outf;
int linenumber,linecounter=0,linepresent;
char filename[21];
char detail[21];
char linedetail[21];
char outfilename[21];
char letter,yn='y';
int position;
/*INPUT DETAILS Ask user for file name and line number*/
printf("Please enter an input filename and a linenumber: ");
//scan filename to char string and line number to int variable
scanf("%s %i",&filename,&linenumber);
/*OUTPUT DETAILS Ask user for file name, letter & position, etc*/
printf("Please enter an output filename, a letter and a position:");
scanf("%s %c %i",&outfilename,&letter,&position);
/* Open file for reading */
inf=fopen (filename,"r");
outf=fopen(outfilename,"r");
/*check that file exists*/
if (inf!=NULL) {
直到这里一切正常!然后我尝试找出outf文件是否已经存在。如果 outf 指向现有文件,它会打印“输出文件已存在,覆盖(y/n):”
但是,一旦打印出来,我就会打开错误窗口!这可能是一个非常菜鸟的错误——我还在学习 C。如果没有这样的文件,程序会正常完成并绕过 if 语句。
if (outf!=NULL){
printf("Output file already exists, overwrite (y/n):");
scanf("%c",yn);
}
if (yn=='y'){
/*keep reading to end of file*/
while (feof(inf)==0) {
linecounter++;
/*read each line and store the line number in detail[WORDS GO HERE]*/
fscanf (inf,"%s", &detail);
/*If we reach the line selected by the user*/
if (linecounter==linenumber){
strcpy(linedetail,detail);
linepresent=1;
}
}
if (linepresent==0) {
printf("File only contains %i lines",linecounter);
}
} else {
exit(1);
}
} else {
printf("Input file not found");
}
printf("%s",linedetail);
/* close the file */
fclose(inf);
fclose(outf);
return (0);
}