i am writing code that basically reads in a text file and only reads in code up to a certain character. It's a simple assembler that needs to read in assembly code whilst discarding comments that follow after '#' sign. For example code line like this:
Code:
addi $3,$0,40 # j = 40
needs to be read in like this:
and here is my code so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LEN 50
static FILE *open_file (char *file, char *mode)
{
FILE *fptr = fopen (file, mode);
if (fptr == NULL){
perror ("Unable to open file"); /* if file is not found prints error message */
exit (EXIT_FAILURE);
}
return fptr; /* returns a pointer */
}
int main (int argc, char *argv[])
{
int array_pos = 0, array_elem;
char letter, word[LEN];
FILE *fptr;
fptr = open_file (argv[1], "r");
do
{
letter = fgetc (fptr);
if (letter != '#')
{
word[array_pos] = letter;
array_pos++;
}
else
{
word[array_pos] = '\0';
word[array_pos + 1] = '\n';
array_pos = 0;
printf ("%s\n", word);
}
} while (letter != EOF);
fclose (fptr);
//printf ("%s\n", word);
return 0;
}
So I want it to read in everything up to the "#' and then go to new line. I have a small amount of experience using fgetc, but I thought if after it reads stuff I want it to read in, I simply put '\0' to indicate end of string and then put in '\n' to make it go to the next line, but I cant get it to work. What do I do to make it ignore any text after '#' ?