Hello,
Let me preface this question with I have been up and down google to no avail looking for the problem. I'm having a problem using iterators and STL with file IO, here is the code:
I have proven I'm at least writing out the correct number of bytes, but I'm not reading in anything - vi.size() comes up as 0. This feels like such a silly problem, and I'm hoping someone can give me a quick hand squaring it away.
#include <vector>
#include <fstream>
#include <algorithm>
#include <cstdlib>
#include <iostream>
usingnamespace std;
int main()
{
vector<int> vi;//vector to be filled
ifstream vi_dump("vi.txt"); //open for read
if (!vi_dump)
{
cerr<<"couldn't open file";
exit(1);
}
copy(istream_iterator<int> (vi_dump),
istream_iterator<int> (),
back_inserter(vi));
}
1 2 3 4 5 6 7 8 9 10 11
copy() writes the file's data into vi.
There's one quirk here that novices might find surprising. If we'd written:
copy(istream_iterator<int> (vi_dump),
istream_iterator<int> (),
vi);
The code wouldn't have compiled, because the third argument isn't an iterator.
vi.begin() is much worse because vi is empty at this stage.
If the container to which you are writing is empty, you need to use a special type of an iterator.
back_inserter(vi) returns a special output iterator that automatically causes vi to allocate storage for incoming data as needed.
I'm messing about with it even as we speak.
It seems it all depends on how the file is written and read.
Like you say, I does not behave quite the way you would expect.
I'm still experimenting :-)
Yes, I understand it now.
It is all to do with the way the file is wriiten and then read.
We were dumpng the vector to file in binary format. The copy function is expecting standard stream format - that is why nothing was being read back in.
You can copy out a a file and copy in from a file - but it is stanard formatting stream stuff.
So if you use the the write data function, you will have to use the read function.
So with all that said, here is how you would 'copy' a vector to a ostream and back from a istream (in this case we are using files streams).
p.s it wouldn't matter if the files open modes include ios::binary.