TITLE: copying a file's contents into a string (Newsgroups: comp.lang.c++, 22 Mar 2000) LEWIS: Ryder Lewis > I'm trying to copy the contents of a file into a string, and have had > very bad performance problems using the method in the code below. Is > there a way to copy the contents of the file all at once, instead of > appending the file one char at a time to the string? KUEHL: Dietmar Kuehl Just read the file when constructing the string: int main() { std::ifstream in(filename); std::istreambuf_iterator beg(in), end; std::string str(beg, end); } However, unless the library implementation uses some specializations this is not likely to be as efficient as possible. If memory is not to much of an issue and if it is acceptable if temporarily twice the size of a string is occupied, you can do this which is probably the fastest approach without hacking up some stream buffer: int main() { std::ifstream in(filename); std::string str; { std::ostringstream out; out << in.rdbuf(); str = out.str(); } } The 'std::ostringstream' is used in a separate scope to have the allocated memory released when it is no longer used: Otherwise the 'out' would hold a copy of the file whic is not really used but which would occupy possible lots of memory. ... However, it would be really nice if the first version would be really efficient without the additional requirement of temporarily using lots of memory. Looks like something I can hack at least for my implementation of the standard C++ library... _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com