第二次调用
copy
时文件还没有准备好读取。
(感谢Piotr Skotnicki在评论中的回答)
调用
flush
可以使程序正常工作:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <fstream>
int main()
{
std::string path("numbersfile");
std::vector<int> myVector{1,16,32,64};
std::vector<int> newVector{};
std::ofstream FILE(path,std::ios::out | std::ofstream::binary);
std::copy(myVector.begin(),myVector.end(),std::ostreambuf_iterator<char>(FILE));
FILE.flush();
std::ifstream INFILE(path,std::ios::in | std::ifstream::binary);
std::istreambuf_iterator<char> iter(INFILE);
std::copy(iter,std::istreambuf_iterator<char>{},std::back_inserter(newVector));
return 0;
}
ofstream
在创建ifstream
时仍然处于作用域内。如果此时调用了ofstream
的析构函数,那么文件也将准备好供ifstream
使用。在下面的程序中,ifstream
被自动销毁:
#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>
std::string filename("numbersfile");
std::vector<double> myVector{1.342, 16.33, 32.1, 12364};
void write_vector_to_file(const std::vector<double>& myVector, std::string filename);
std::vector<double> read_vector_from_file(std::string filename);
int main()
{
write_vector_to_file(myVector, filename);
auto newVector{read_vector_from_file(filename)};
return 0;
}
void write_vector_to_file(const std::vector<double>& myVector, std::string filename)
{
std::ofstream ofs(filename, std::ios::out | std::ofstream::binary);
std::ostream_iterator<double> osi{ofs," "};
std::copy(myVector.begin(), myVector.end(), osi);
}
std::vector<double> read_vector_from_file(std::string filename)
{
std::vector<double> newVector{};
std::ifstream ifs(filename, std::ios::in | std::ifstream::binary);
std::istream_iterator<double> iter{ifs};
std::istream_iterator<double> end{};
std::copy(iter, end, std::back_inserter(newVector));
return newVector;
}
std::copy
后面加上FILE.flush();
? - Piotr Skotnicki