Ok, so I'm trying to write an emulator for a simple processor architecture and I've ran into a strange problem. I decided to read the input code once through to see how many lines there were, then set up an array of that length, and then go through the file a second time to read the code into the array. Each line is 8 hex characters long.
The first time through, everything goes as normal, but the second time through, fgets reads the entire file, which is wierd.
It's been a while since I've programmed in C and even then I didn't do a whole lot of it, so it's probably something very simple, but I'm stumped. And google didn't help either.
Anyway, here's the relevant code.
void truncate(char *string)
{
int l = strlen(string);
if(string[l-1] == '\n')
string[l-1] = '\0';
}
int main(int argc, char *argv[])
{
if(argc < 2) //check right number of arguments
printf("USAGE: %s <input filename> <optional arguements>\n", argv[0]);
else
{
int size = 0;
int i = 0;
FILE *inf;
inf = fopen(strcat(argv[1],".o"), "r"); //open file
if(inf == NULL)
{
fprintf(stderr, "ERROR: Can't open '%s' for reading!\n", argv[1]);
}
else
{
char varline[8];
while(fgets(varline, 128, inf) != NULL) //find file size
size++;
rewind(inf);
char program[size][8]; //create array to hold all code
for(i=0;i<size;i++) //fill array from file
{
fgets(program[i], 128, inf);
truncate(program[i]); //remove newline character from string
}
fclose(inf); //close file
}
}
}
For example. If the file has four lines of code
00000111
00005AB4
00006500
00009D01
printing out program[0] gives me
0000011100005AB40000650000009D01
and printing program[1] gives
00005AB40000650000009D01
P.S. I'm using the GCC compiler on a UNIX machine.