Dealing with whitespaces whilst reading a file
The aim of my code is to read in a code in a text file and discard comments, i.e. any characters after '#'. So for example, line like this:
Code:
main: addi $3,$0,40 # j = 40
is transformed into:
I have written a code that does just that. However, if the line only contains a comment I end up with an array of empty characters. Here is my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LEN 60
void comment_remove (char word[LEN])
{
char temp[LEN];
int i, j;
for (i = 0; i < LEN; i++){
if (word[i] != '#'){
temp[i] = word[i];
}else{
temp[i] = '\0';
}
}
i = 0, j = 0;
while (i < LEN){
if (temp[i] != ' '){
word[j] = temp[i];
i++;
j++;
}else{
i++;
}
}
}
static FILE *open_file (char *file, char *mode)
{
FILE *fptr = fopen (file, mode);
if (fptr == NULL){
perror ("Unable to open file");
exit (EXIT_FAILURE);
}
return fptr;
}
int main (int argc, char *argv[])
{
int array_pos = 0;
char letter, word[LEN];
FILE *fptr;
fptr = open_file (argv[1], "r");
do{
letter = fgetc (fptr);
if (letter != '\n'){
word[array_pos] = letter;
array_pos++;
}else{
word[array_pos] = '\0';
array_pos = 0;
comment_remove (word);
printf ("%s\n", word);
}
} while (letter != EOF);
fclose (fptr);
return 0;
}
So for example, text file like this:
Code:
# register allocation:
#
# $3 = j
# $4 = a = i - 0
# $5 = b = i - 1
# $6 = c = i - 2
# $7 = t1
# $8 = t2
# $9 = t3
main: addi $3,$0,40 # j = 40
comes out like this:
My question is how can I deal with the empty arrays in the beginning of the file?