Dynamic Memory Allocation for fstream - C++

kuphryn

Senior member
Jan 7, 2001
400
0
0
Hello.

I have a question about dynamically allocating enough memory space to read data/text from a file no matter if the user wants to read one line or the entire file.

For example let say I have a text file with 10 lines to text:

aaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccc
ddddddddddddddddddd
eeeeeeeeeeeeeeeeee
ffffffffffffffffffffffffffffffffff
gggggggggggggggg
hhhhhhhhhhhhhhh
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
jjjjjjjjjjjjjjjjjjjjjjjjjj

1) Let say I want to read the first line so I could make changes to it (in memory first of course). Is there a way to dynamically allocate enough memory so the entire line would fit in a pointer to char? I can allocate the memory space, but the problem is I do not know the size to start out.

2) Let say I want to read the entire file (everything). Is there a way to dynamically allocate enough memory so the entire file would fit in a pointer to char?

Ex:

char *ptr;
ptr = new char[????] <------- what size relative to the lengh of the line or entire file?

Thanks,
Kuphryn
 
 

Agaemon

Member
Mar 17, 2001
30
0
0
The way to do this is to allocate a set chunk of memory, say 1k, and read from the file, filling it up. Then if there is still more in the file realloc or malloc more memory and read in more.
 

singh

Golden Member
Jul 5, 2001
1,449
0
0
Here's an example program in C++:

#include <iostream.h>
#include <fstream.h>



void main ()
{
long file_size = 0;
char *pBuf = NULL;


/* Open file using ifstream class */
ifstream file ("test.file", ios::in|ios::binary);

/* Seek to end of file */
file.seekg (0, ios::end);

/* Read position = file size */
file_size = file.tellg();

/* Seek to beginning again */
file.seekg(0, ios::beg);

/* Dyn. allocate memory */
pBuf = new char[file_size];

/* Read the file data */
file.read(pBuf, file_size);

/* Close */
file.close();

cout << "File Size = " << file_size << "\n";
cout << "Read bytes:\n";
cout << pBuf << "\n";
}


 

kuphryn

Senior member
Jan 7, 2001
400
0
0
Thanks everyone.

singh: Nice!!! Very straightforward. I forgot about the tellg() member function. Thank you!

Kuphryn