Computing.Net > Forums > Programming > File Array & Character

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

File Array & Character

Reply to Message Icon

Name: puwados
Date: November 19, 2002 at 18:07:18 Pacific
OS: Windows XP
CPU/Ram: P3 450
Comment:

In C++, can I read a file and get each character put into the Array without knowing the size of the Array???




Sponsored Link
Ads by Google

Response Number 1
Name: Guy
Date: November 20, 2002 at 16:50:34 Pacific
Reply:

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 area

If 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


0
Reply to Message Icon

Related Posts

See More







Post Locked

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


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: File Array & Character

Pointer to array of character pointers? www.computing.net/answers/programming/pointer-to-array-of-character-pointers/2809.html

c++ character array www.computing.net/answers/programming/c-character-array/9714.html

C arrays of strings from a file www.computing.net/answers/programming/c-arrays-of-strings-from-a-file/14025.html