Succinctly, you can't do what you are seeking to do, namely change the size of a global array after the program starts executing.
Consequently, you will need to use dynamic memory allocation instead. Change the declaration to:
static char *b = 0;
The static
means it can only be accessed by the functions in this file, but since you don't show any other files, that won't matter. If you do need to access the variable in other files, you'll need a header to declare the variable and you'll remove the keyword static
.
The use of char *b
in place of char b[]
means you can allocate the space you need with malloc()
or one of its friends (using #include <stdlib.h>
to declare them), and then use free()
to release the memory when you're done. You will also need to tell other parts of the software how much memory is allocated, so there'll be another variable such as:
static size_t b_size = 0;
which you will set to the size when you allocate it. After you've allocated the memory, you can use b
just as if it was an array.
Don't forget to check that the allocation succeeded.
As to finding file size, you can either use a platform-specific function such as stat()
on POSIX-based systems (Unix et al), or you can use
fseek()
and
ftell()
. These are reasonably portable, but are limited to handling files small enough that the size can be represented in a long
. On 64-bit systems, that's not a problem; for 32-bit systems, it can be a problem if you might need to deal with multi-gigabyte files (but of course allocating multiple gigabytes of memory is also fraught with 32-bit systems).
Finally, for now, the name b
is not a very good name for a global variable. It is generally a good idea to use more meaningful names, especially for global variables. (I use names like b
as local variables in a function; I'd not use it as a global in any plausible circumstances.)