C++ doesn't have a separate way of performing a realloc() call, using its "new" allocator. But C++ does support the older C methods using malloc/free and that system does, of course, support realloc().
If you are NOT reading up numbers and strings and the like, but are just reading up chars, then you could do as Tensai suggests and use a POSIX function like fstat(). Unfortunately, it isn't in the standards. So you cannot always count on it.
You can open the file in binary mode, seek to the end of the file, get the seek position, and if you assume that it means what it probably means (it's an assumption, of course, but often right) then you could use that as another way of estimating.
Finally, if you just want to use a very reliable method, you could do something like what is below. It uses C++ I/O. But since you have to use the C malloc system to get access to the realloc() function in C++, it also requires the cstdlib include file. The code here starts out assuming a small file, but doubles its allocations every time the current allocation is exceeded, so it grows geometrically. Also, if it runs into limitations using that mode (memory is getting very tight for some reason), it switches over to a add-by-bits mode where it creaps up on the absolute memory limits as it continues to read up the file. It's pretty robust. Of course, it cannot give you memory when there isn't enough for the file. For that, you'd need to switch to a file caching system if you really need something like that.
#include
#include
using namespace std;
char * readfile( istream &f ) {
int c;
char *result, *b;
size_t maxn, extend, cn;
enum { greedy, miserly } mode= greedy;
if ( f == 0 ) return 0;
result= (char *) malloc( maxn= extend= 1000U );
if ( result == 0 ) return 0;
for ( cn= 0, c= f.get(); c != EOF; c= f.get() ) {
while ( cn >= maxn && extend > 0 ) {
b= (char *) realloc( result, maxn + extend );
if ( b != 0 ) {
result= b;
maxn += extend;
if ( mode == greedy ) extend= maxn;
break;
}
mode= miserly;
extend >>= 1;
}
if ( cn >= maxn && !extend ) {
free( result );
return 0;
}
result[cn++]= c;
}
result[cn++]= '\0';
return (char *) realloc( result, cn );
}
There are still other ways. But a lot depends on exactly how your encryption eventually works. (I can see your simple example, but I don't assume that is where you are going.) If it uses fixed block sizes, you have many more options that could easily support petabyte files without problems. But if your algorithms require random access at random locations, then a lot of those ideas stop working so well. I've not mentioned any of these ideas here, though. No idea if you care.
EDIT: To SKH... Using a linked list for a 'char' would not make much sense. You could do it. But it's an unbelievably excessive waste of memory and cpu time and I would LOVE to see the encryption algorithm working on that structure!!