• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Dynamic Memory Allocation for fstream - C++

kuphryn

Senior member
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
 
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.
 
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";
}


 
Thanks everyone.

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

Kuphryn
 
Back
Top