下面的問題的主要描述,它發生的地方。但簡單地說,我不知道爲什麼我詢問後爲什麼會收到錯誤消息努力理解文件指針?
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