下面的问题的主要描述,它发生的地方。但简单地说,我不知道为什么我询问后为什么会收到错误消息努力理解文件指针?
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);
}
不要忘记'&':'scanf(“%c”,&yn)' – pmg
如果你发现有问题的行......你为什么不尝试一个简单的程序,只说'int main ){char yn ='y'; scanf(“%c”,yn);返回0; ''...当这个崩溃的职位是这样吗? : -/*(下次要考虑的事情是,当问题被减少到最小的情况下,最好的情况会产生错误,其他所有事情都会被带出。)* – HostileFork
谢谢,我确实需要改进我的提问技巧!为每个人的耐心欢呼! – user1083734