Try with a function returning a calloc
-ed (see calloc(3) man page) pointer of instr
.
So
instr* read_file(const char*filename)
{
instr* arr=NULL;
int len=0, size=0;
FILE* f= fopen(filename, "r");
if (!f) { perror(filename); exit(EXIT_FAILURE); };
while (!feof (f)) {
if (len>=size-1) {
int newsize = 5*len/4+50;
instr* newarr = calloc(newsize, sizeof(instr));
if (!newarr) { perror("calloc"); exit(EXIT_FAILURE); };
if (arr) memcpy (newarr, arr, sizeof(instr)*len);
free (arr);
arr = newarr;
size = newsize;
};
if (fscanf(f, "%d %d %d",
&arr[len]->op, &arr[len]->l, &arr[len]->m)<3)
break;
len++;
}
arr[len]->op = -1; // end of array marker
fclose(f);
return arr;
}
The above function reads a heap allocated array of instr
[in pointer arr
] and is reallocating it as needed.
Don't forget to free
the result of read_file
near the end of your program.
With the above code, you can read a lot of instr
(perhaps millions on an average PC, and much more than 500). Then you'll code
int main() {
instr* code = read_file("input.txt");
print_program(code);
// at the very end of main
free(code);
}