将空格添加回装配程序

时间:2016-03-09 00:15:06

标签: c assembly

到目前为止,我被赋予了一个汇编程序,用于以 - 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 个答案:

答案 0 :(得分: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;
}