我有一個'C'程序遇到了一個奇怪的問題..我在包含「feof(fp)」的行中出現段錯誤.. 我是試圖在Linux上運行..幫助需要關於文件指針處的段錯誤
我甚至用gdb命令回溯程序.. 但它是沒有用的..
檢查我的樣本代碼..
char buf[2000],str[15],lno[5],def[15],ref[15],tmp[15],ch,ifile[20],ofile[20];
int i,j,oldi,count,c,r,d,f,t,lc=0;
FILE *fp=NULL,*fpo=NULL;
void xyzstart()
{
/*
*Some operation that is not at all concerned with the file
*
*/
}
int main()
{
printf("Enter the name of the input file\n");
gets(ifile);
fp=fopen(ifile,"r");
if(fp==NULL)
{
printf("Error");
exit(0);
}
printf("Enter the name of the output file\n");
gets(ofile);
fpo=fopen(ofile,"w");
if(fpo==NULL)
{
printf("Output file couldn't be opened\n");
exit(0);
}
while(!feof(fp))
{
fgets(buf,sizeof(buf),fp);
count++; //Count the number of lines in a file
}
rewind(fp); //move the file pointer to the beginning of the file
while(!feof(fp)) //Error is here!! Segmentation fault (Core Dumped)!!
{
clear(); //User defined function which clears all the memory
if(count==lc)
{
nodef(); //User defined function which doesn't reads from or writes into a file
noref(); //User defined function which doesn't reads from or writes into a file
print(); //User defined function which writes the values to output file
break;
}
fgets(buf,sizeof(buf),fp);
{
i=0;
lc++;
while(buf[i]!=' ') //read until it encounters a space..
{
lno[i]=buf[i];
i++;
}
lno[i]='\0';
//puts(lno);///
}
i++;
oldi=i;
ch=buf[i];
switch(ch)
{
case 'x': xyzstart(); break;
default: printf("Nothing found");
}
}
fclose(fpo);
fclose(fp);
return 0;
}
我真的不知道該怎麼做!任何人都可以請幫我嗎? 在此先感謝!
下面是既清晰又xyzstart()的代碼 無效明確()
{
memset(buf,'\0',sizeof(buf));
memset(lno,'\0',sizeof(lno));
memset(def,'\0',sizeof(def));
memset(ref,'\0',sizeof(ref));
i=oldi=0;
memset(str,'\0',sizeof(str));
}
void xyzstart()
{
r=d=c=0;
for(;;c++,i++)
{
if(buf[i]==' ')
break;
if(buf[i]=='(') break;
if(buf[i]==';')break;
if(buf[i]=='\n') break;
if(buf[i]=='=') break;
if(buf[i]=='+' || buf[i]=='-') break;
str[c]=buf[i];
}
str[c]='\0';
if(buf[i]=='=')
assignment();
else if(buf[i]=='+' || buf[i]=='-') //Increments or decrements
incdec();
else if(buf[i]=='(')
udefined();
}
你確定你的文件名少於19個字符嗎?如果他們不是,你會得到一個緩衝區溢出。 – 2011-06-06 17:13:32
你正在使用'feof'錯誤。'feof'函數不會檢測下一次讀取是否會失敗,因爲文件位於最後;它測試最後的失敗是否是由於文件處於末尾。而且你使用它沒有失敗 – pmg 2011-06-06 17:41:36