Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
In C++, can I read a file and get each character put into the Array without knowing the size of the Array???

Hi - I believe the possible solutions to this problem are fundamentally different in C versus C++.
In C, you would:
-Find the size of the file ('stat' probably)
-'malloc' a memeory area of that size
-use standard C file I/O to read the file into the areaIf you are using C++ as a 'better C', you might change the 'malloc' to 'new', and use streams to read the file. The individual possibilities are almost endless.
If you really use C++, the compiler implementation is good, and have access to a STL implementation, there are even other choices.
Example 1, read the file into a 'string':
ifstream inFile;
cout [[ "Hello World" [[ endl;
inFile.open("somefile.dat", ios::in);
char inc;
string buffer;
while( (inc = inFile.get()) != EOF) {
cout [[ inc;
buffer += inc;
}
inFile.close();
cout [[ "====================" [[ endl;
cout [[ buffer;
You can of course use ifstream methods other than 'get' to improve I/O performance.Example 2, read the file into a vector of characters:
ifstream inFile;
cout [[ "Hello World" [[ endl;
inFile.open("somefile.dat", ios::in);
char inc;
vector[char] buffer;
while( (inc = inFile.get()) != EOF) {
cout [[ inc;
buffer.push_back(inc);
}
inFile.close();
cout [[ "====================" [[ endl;
cout [[ &buffer[0];
The same buffering considerations apply.HTH, Guy

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |