2012-04-24 62 views
-1

对于一个项目,我必须将编译好的汇编语言翻译成内存位置和操作码。我需要解析文件两次,我用strtok()来做到这一点。但是,我的程序没有达到第二个循环。 (我把一个打印语句放在开头,所以我很确定它没有达到它。)我的想法是指针在文件的末尾,所以我试着把倒带(文件名)和fseek(文件名,0 ,SEEK_SET),但似乎没有解决问题。有什么想法吗?谢谢。文件结尾的原因

编辑:这里的一些代码(第二个密码),

j=1, i=0; 
/*SECOND PASS*/ 
fseek(opcode,0,SEEK_SET); 
char string[5]; 
while((fgets(str, buffer, file))!=NULL){/*getting line*/ 
printf("it got here. yup."); 
fputs(memLoc(j-1), opcode); /*inserts the location in memory to file*/ 
fputs(" ", opcode);/*puts a space in the file*/ 

int state=0; /*state to see if on first or second part of code*/ 

for(i=0; i<buffer; i++){ /*gets rid of extra new line chars*/ 
    if(str[i]=='\n'){ 
    str[i]= '\0'; 
    break; 
    } 
} 
cp = xerox(str); 
token = strtok(cp, delimiters); 
printf("%s ",token); 
/*if it's not a label, find corresponding opcode and insert into file, 
switch state, if it's a label, don't switch state*/ 
    if((token!=NULL)&&token[strlen(token)-1]!=':'){ 
     fputs(findOpCode(token), opcode); 
     state=1; 
    } 
    else state=0; 

/*if it should be an opcode, insert corresponding opcode into file, 
if it should be a location, find and insert where it should be*/ 
    for (;token = strtok(NULL, delimiters);){ 
    printf("%s ",token); 
     if(token!=NULL) 
      if(state==0){ 
      fputs(findOpCode(token), opcode); 
      } 

      else if(state==1){ 
      fputs(locate(token, fIndex), opcode); 
      } 
     } 
    j++; 
    fputc('\n', opcode);/*next line*/ 
} 
+0

我的想法:显示代码。 – 2012-04-24 01:14:47

+0

只是一个建议:如果您发布有问题的代码的相关部分,您会得到更好的答案。 – andy 2012-04-24 01:16:01

+0

有些代码在这里真的很有用。您最好的选择是发布[SSCCE](http://sscce.org/)。拿起你的代码,将其归结到创建奇怪行为所需的最低限度,然后发布。 – ulmangt 2012-04-24 01:16:51

回答

1

难道你没有倒卷错误的文件吗?你不想倒退你正在阅读和解析的文件吗?如果是这样,它应该是:

fseek(file,0,SEEK_SET); 
2

我做的第一件事是错误检查,您FSEEK:

if (fseek(opcode,0,SEEK_SET) == -1) { 
    perror("fseek"); 
    exit(1); 
} 

这应该给你更多的信息。