2016-03-09 40 views
0

到目前爲止,我收到了一個彙編程序,該程序以一行開始,如 - main: mov %a,0x04 ; sys_write。有些行包含標籤(在末尾是帶有分號的詞),有些則不包含。 ;之後的所有內容都是評論,需要刪除。需要刪除空白區並重新放入,以便成品看起來像這樣 - main: mov %a,0x04。我已經花了很多時間了,想知道你們是否知道如何放入空格,因爲目前看起來像這樣 - main:mov%a,0x04。任何可以普遍增加白色空間的方式將不勝感激。將白色空間添加到我的彙編程序中

int i; 
char line[256]; 
while(fgets(line,256,infile) != NULL) 
{ 
    char label[256]; 
    int n = 0; 
    for(i=0; i<256; i++) 
    { 
     if(line[i] == ';') // checks for comments and removes them 
      { 
      label[n]='\0'; 
      break; 
      } 
     else if(line[i] != ' ' && line[i] != '\n') 
      { 
      label[n] = line[i]; // label[n] contains everything except whitespaces and coms 
      n++; 

      } 
    } 

    char instruction[256]; 
    for(n =0; n<strlen(label);n++) 
    { 
     //don't know how to look for commands like mov here 
     // would like to make an array that puts the spaces back in? 
    } 

    // checks if string has characters on it. 
    int len = strlen(label); 
    if(len ==0) 
     continue; 
    printf("%s\n",label); 
} 
fclose(infile); 
return 0; 
+1

':'是一個冒號,','是** **半結腸。 – Olaf

+0

是的,所以在分號後不要打印任何東西。冒號前面的單詞被稱爲標籤,例如main:或name:etc ... – Jason

+0

您應該只能刪除多餘的空格(即一個接一個),並且不要試圖將它們放回... – Jester

回答

1

我將字符串分隔爲空格之間的子字符串,然後在它們之間添加一個空格。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(){ 
FILE *infile=fopen("assembly","r"); 
char line[256]; 
while(fgets(line,256,infile) != NULL) 
{ 
    char* tok=strtok(line,";");      //search for comma 
    char* label=malloc(strlen(tok)*sizeof(char)); //allocate memory for 
                //string until comma 

    strcpy(label,"");        //clean string 
    tok=strtok(tok," ");       //search for space 
    while(tok != NULL){ 
     if(strlen(label)>0)       //when not empty, 
      strcat(label," ");      //add space 
     strcat(label,tok); 
     tok=strtok(NULL," "); 
    } 
    printf("%s_\n",label); 
    free(label); 
} 
fclose(infile); 
return 0; 

如果您仍然想這樣做你的方式,我會做這樣的

(...) 
    else if((line[i] != ' ' && line[i] != '\n')||(line[i-1] != ' ' && line[i] == ' ')) 
     {     // also copy first space only 
     label[n] = line[i]; // label[n] contains everything except whitespaces and coms 
     n++; 
     } 
    } 
    printf("%s\n",label); 
} 
fclose(infile); 
return 0; 
} 
+0

'malloc (strlen(tok)* sizeof(char))'應該是'malloc(strlen(tok)+ 1)'。很顯然,如果所有元素都是以空格分隔開始的,那麼這個代碼纔會起作用,所以如果標籤和冒號之間存在空格,或者逗號兩側存在空格,它將不起作用。另外,'if(label [0]!='\ 0')'比每次通過循環調用'strlen()'效率更高。 –

+0

嗨,感謝您的輸入,但如果我不想複製第一個空格,那麼怎麼辦?因爲冒號後我需要4個空格,直到mov,如果它的mov%b,0x01例如本身應該有2個縮進標籤。關於這一點最難的部分是將其轉換爲寫入格式。 – Jason

+0

您可以找到冒號併爲2個製表符縮進添加4個空格或\ t \ t。 –