C编程打开并从文件中读取

时间:2013-11-17 22:30:00

标签: c

int main(void){
     FILE *ifp;                 //input file pointer  
     int totalClock;            //total clock count
// BEGIN OPERATIONS=============================
     ifp=fopen("prog1.asy.txt", "r");
     system("PAUSE");
     assert(ifp!=NULL);
//populate the instMem with inst===================
     int i=0;
     //system("PAUSE");
     for (i=0;i<512;i++)
     {

    inst temp=parser(ifp);
    if (temp.opcode==-1)
       break;
    instMem[i]=temp;
    printf("%s\n", instMem[i].rawCode);
}
printf("\n%d instructions parsed\n", i-1);
system("PAUSE");// PAUSE TO CHECK CODE PARSING IS CORRECT========
int cont=0;
while (cont==0){
      //begin sim================================================
      //initialize the mem=======================================
      int i;
      for (i=0;i<512;i++)
          data[i]=0;
      for (i=0;i<32;i++)
          reg[i]=0;
      IF_Time=0;
      ID_Time=0;
      EX_Time=0;
      MEM_Time=0;
      WB_Time=0;
      //prompt input parameters===================================
      printf("Memory access time: c=");
      scanf("%d", &c);
      printf("\nMultiply time: m=");
      scanf("%d", &m);
      printf("\nExecute time: n=");
      scanf("%d", &n);
      assert(c>0);
      assert(m>0);
      assert(n>0);    
      //start execution now that the program has been broken to unparsed strings====
      while (0==0)
      {
            WB();
            MEM();
            if (MEM_WB.instruction.opcode==HALT)
               break;
            EX();
            ID();
            IF();
            totalClock++;
            system("PAUSE");
      }

      //PRINT RESULTS=============================================


      printf("Run again with new parameters? 0=yes");
      scanf("%d", &cont);      
     }
  fclose(ifp);  
  system("PAUSE");  
  return 0;
}

struct inst parser(FILE *ifp){

       char str[100];
       struct inst temp;
       if (fgets(str, 100, ifp)==NULL) {
          inst temp={"NULL", -1,0,0,0};
       }
       else {
       inst temp={str, 0,0,0,0};
       puts(str);
       }
       return temp;
}

我正在尝试读取测试文件,以便我可以将其解析为字符串以供日后分析。它打开测试文件但它没有读取代码中的测试行。有什么我做错了。

2 个答案:

答案 0 :(得分:1)

您的parser函数只从文件中读取一次,并且对结果不执行任何操作(因为temp将是if分支的本地变量,而不是函数)。首先要从inst中删除inst temp = ...以查看它是否读取了第一条指令。然后,您需要在文件中的所有行上进行该函数循环。

答案 1 :(得分:0)

首先,您需要在此页面上格式化源代码,以使其更具可读性。

对于parser(),我认为你不能返回一个结构。所以请改用指针。并且,正如Mihai所提到的,“temp”是位于堆栈上的临时变量,当从函数解析器()返回时它将被销毁。

我没有在代码片段中看到变量的声明:

  IF_Time=0;
  ID_Time=0;
  EX_Time=0;
  MEM_Time=0;
  WB_Time=0;

所以我假设您可以删除一些未使用的代码以使问题清楚。

最后一点是:分析日志文件,shell脚本比C更合适。如果你不在UNIX / Linux盒子上工作,你也可以使用Perl / Python。当用于分析日志文件时,它们都不易出错且易于调试。