I’m attempting to grab each line from a TXT file and then pass that line into variables, which I will match up in an if statement. My txt file is:
add $t0, $t1, $t2
addi $t0, $t1, 30352
It properly removes the commas and sends "add", "$t0", "$t1", "$t2" to their respective variables and then translates them to the binary representation using if statements. It works for every variable except for $t2 because there is some kind of hidden line break that I cannot for the life of me figure out how to remove. My if statement looks like
else if(strcmp("$t2", reg) == 0)
{
return r10;
}
which should be returning 01010 but instead never evaluates true.
How can I cleanse this of the line break in C?
Update: Here’s how I’m reading the file
FILE *fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
void sendLine()
{
//Open file, check it's not empty
fp = fopen("mymipsfile.txt", "r");
if (fp == NULL)
{
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu:\n", read);
printf("%s", line);
remove_all_chars(line, ',');
interpertLine(line);
decodeLine(0);
printf("\n");
}
fclose(fp);
if (line)
{
free(line);
}
exit(EXIT_SUCCESS);
}
And here is how im splitting it into the variables
void interpertLine(char currentLine[])
{
//Extract the first token
char * token = strtok(currentLine, " ");
op = token;
//Loop through the string to extract all other tokens
int i = 0;
while( token != NULL ) {
//printf( " %s\n", token ); //printing each token
token = strtok(NULL, " ");
if(i == 0)
{
rs = token;
}
else if (i == 1)
{
rt = token;
}
else if (i == 2)
{
rd = token;
}
i++;
}
}
>Solution :
Simply limit the comparing length to visible characters only:
else if (strncmp("$t2", reg, sizeof("$t2") - 1) == 0)
{
return r10;
}
Note: I’m using ‘sizeof() – 1’ to prevent comparison the trailing null termination byte (0), existing on the end of each string literal "…."