c - 将空格添加回我的汇编程序中

标签 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;

最佳答案

我将字符串分成空格之间的子字符串,然后在它们之间添加一个空格。

#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;
}

关于c - 将空格添加回我的汇编程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35880602/

相关文章:

c - 在 2d 数组 3x3 幻方中查找重复值

c++ - GMP 如何在任意数量的字节上存储它的整数?

assembly - 查找打包文件OEP的方法

assembly - 构建带有递归函数的.so

c - postfix 计算器遇到段错误问题

c - 是否有实用程序可以打印 C 程序的函数调用序列?

assembly - Linux 内核从实模式到保护模式的转换

algorithm - 使用增量和乘以 2 生成任意数字

c - simd 存储延迟

c - 解析字符串并减去子字符串