From: Gerd von Egidy Date: Tue, 9 Mar 2010 10:33:13 +0000 (+0100) Subject: add copy_stream to filefunc and use it in copy_file X-Git-Tag: v2.6~112^2~14 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=a1e7d2a7182cfadffd45cfdb03445ea4c1047641;p=libi2ncommon add copy_stream to filefunc and use it in copy_file --- diff --git a/src/filefunc.cpp b/src/filefunc.cpp index 4b67c47..469b2b3 100644 --- a/src/filefunc.cpp +++ b/src/filefunc.cpp @@ -453,27 +453,49 @@ bool write_file(const std::string& path, const std::string& data) */ bool copy_file(const std::string& src, const std::string& dest) { - std::ifstream input( src.c_str(), std::ios::in | std::ios::binary ); - if (!input) + std::ifstream input( src.c_str(), std::ios::in | std::ios::binary ); + if (!input) + return false; + + std::ofstream output( dest.c_str(), std::ios::out | std::ios::binary | std::ios::trunc); + if (!output) + return false; + + // Out of disc space? + if (!copy_stream(input,output)) + { + output.close(); + unlink(dest); + return false; + } + + return true; +} + +/** + * Copy streams in 4k blocks. + * + * @param is source stream + * @param os target stream + * @return true if all is ok, false on error + */ +bool copy_stream(std::istream& is, std::ostream& os) +{ + if (!is) return false; - std::ofstream output( dest.c_str(), std::ios::out | std::ios::binary | std::ios::trunc); - if (!output) + if (!os) return false; char buffer[4096]; - while (input.good()) + while (is.good()) { - input.read(buffer, sizeof(buffer)); - output.write(buffer, input.gcount()); - - // Out of disc space? - if (!output.good()) - { - output.close(); - unlink(dest); + is.read(buffer, sizeof(buffer)); + os.write(buffer, is.gcount()); + + // Can't write? + if (!os.good()) return false; - } } return true; diff --git a/src/filefunc.hxx b/src/filefunc.hxx index c0c01f7..920a10f 100644 --- a/src/filefunc.hxx +++ b/src/filefunc.hxx @@ -144,6 +144,7 @@ std::string read_file(const std::string& path); bool write_file(const std::string& path, const std::string& data); bool copy_file(const std::string& src, const std::string& dest); +bool copy_stream(std::istream& is, std::ostream& os); std::string basename(const std::string& path);