Reputation: 7
So far I was given a piece of assembly program for an assignment that started of with lines like - main: mov %a,0x04 ; sys_write
. Some lines contain the label (which is the word with the semi colon on the end) and some dont. Everything after the ;
is a comment and need to be removed. The whitespaces need to removed and put back in so the finished product would look something like this -main: mov %a,0x04
. I've spent many days on this and wondered is u guys knew how to put the whitespaces in because currently it looks like this - main:mov%a,0x04
. Any sure way of universally adding the white spaces in would be appreciated.
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;
Upvotes: 0
Views: 86
Reputation: 11
I separate the string into sub-strings between spaces and then add a space between them.
#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;
If you still want to do it in your way, I would do it like this
(...)
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;
}
Upvotes: 1