On 27 Apr 2004 05:07:14 -0700,
foxykav@hotmail.com (Foxy Kav) wrote:
[color=blue]
>Hi, another question from me again, i was just wondering if anyone
>could give me a quick example of reading data from a file then placing
>the data into an array for some manipulation then reading that array
>back into another file.
>
>I've tried, but i can only read the data and place it on the screen, i
>cant get it into an array.[/color]
If you want the whole file in an array (or vector), you can do:
#include <vector>
#include <fstream>
#include <algorithm>
#include <iterator>
int main()
{
//open the file in binary mode (to get raw chars)
std::ifstream ifs("myfile.txt", std::ios_base::binary);
//create an iterator pair over the contents of the file
std::istreambuf_iterator begin(ifs), end;
//copy the iterator range into a vector
std::vector<char> contents(begin, end);
//close the file
ifs.close();
//change a character - contents contains the whole file here
//be careful to check how big contents is (via contents.size()).
contents[0] = 'q'; //or contents.at(0) = 'q'; for bounds checking
//open file again for output
std::ofstream ofs("myfile.txt", std::ios_base::binary);
//write out whole vector in one go:
ofs.write(&contents[0], contents.size());
//everything cleaned up automatically by destructors -
//one of the joys of C++ over C!
}
Tom
--
C++ FAQ:
http://www.parashift.com/c++-faq-lite/
C FAQ:
http://www.eskimo.com/~scs/C-faq/top.html