【发布时间】:2012-10-03 14:18:03
【问题描述】:
我正在做一个程序,我使用 Dev C++。运行我的程序时终止。
在调试时它说'segmentation fault'。我不知道它是否会进入无限循环。
我不知道问题出在代码中的while(!feof(program)) 还是fscanf(...)。
谁能帮忙解决这个问题?请参阅下面的程序:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
fpos_t curDesStart,curDesEnd;
fpos_t curDesLocBackup,curDes;
char *label,*opc,*operands;
char *curMacroName;
FILE *namTab,*desTab,*temp,*program;
namTab=fopen("namTab.txt","rw");
desTab=fopen("desTab.txt","rw");
temp=fopen("temp.txt","w");
program=fopen("program.txt","r");
while(!feof(program))
{
fscanf(program,"%[^\n]%[^\n]%[^\n]",label,opc,operands);
if(!strcmp(label,"MACRO"))
{
fprintf(desTab,"%s%s%s\n",label,opc,operands);
fgetpos(desTab,&curDesStart);
strcpy(curMacroName,label);
while(!strcmp(opc,"MEND"))
{
fscanf(program,"%s%s%s",label,opc,operands);
}
fprintf(desTab,"%s%s%s\n",label,opc,operands);
fgetpos(desTab,&curDesEnd);
fprintf(namTab,"%s%ld%ld\n",curMacroName,curDesStart,curDesEnd);
}
else
{
while(!feof(namTab))
{
fgetpos(desTab,&curDesLocBackup);
fscanf(namTab,"%s%ld%ld",curMacroName,curDesStart,curDesEnd);
if(!strcmp(curMacroName,label))
{
fsetpos(desTab,&curDesStart);
fscanf(desTab,"%s%s%s\n",label,opc,operands);
fprintf(temp,".%s%s%s\n",label,opc,operands);
do{
fprintf(temp,"%s%s%s\n",label,opc,operands);
fgetpos(desTab,&curDes);
}while(curDes<=curDesEnd);
fsetpos(desTab,&curDesLocBackup);
fsetpos(namTab,0);
}
else
{
fprintf(temp,"%s%s%s\n",label,opc,operands);
}
}
}
}
fclose(program);
fclose(namTab);
fclose(desTab);
fclose(temp);
getch();
return 0;
}
【问题讨论】:
-
C++ 与 C 不同(但仅仅使用 dev C++ 编译并不会真正改变您的代码是 C 的事实),因此此链接并不完全适用,但请阅读stackoverflow.com/questions/5431941/…
-
不要使用
feof()来控制输入循环的终止。使用输入函数的结果。feof()可以在您用完输入之后使用,以确定它是由于文件结束条件还是错误 (ferror())。