add copy_stream to filefunc and use it in copy_file
authorGerd von Egidy <gerd.von.egidy@intra2net.com>
Tue, 9 Mar 2010 10:33:13 +0000 (11:33 +0100)
committerGerd von Egidy <gerd.von.egidy@intra2net.com>
Tue, 9 Mar 2010 10:33:50 +0000 (11:33 +0100)
src/filefunc.cpp
src/filefunc.hxx

index 4b67c47..469b2b3 100644 (file)
@@ -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;
index c0c01f7..920a10f 100644 (file)
@@ -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);