Created
March 20, 2015 07:24
-
-
Save magicianzrh/d29d08f4fdd8b3c2f8ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"log" | |
"os" | |
) | |
var target_path string | |
var source_path string | |
func main() { | |
source_path = os.Args[1] | |
target_path = os.Args[2] | |
err := copy_folder(source_path, target_path) | |
if err != nil { | |
log.Fatal(err) | |
} else { | |
fmt.Print("copy finish") | |
} | |
} | |
func copy_folder(source string, dest string) (err error) { | |
sourceinfo, err := os.Stat(source) | |
if err != nil { | |
return err | |
} | |
err = os.MkdirAll(dest, sourceinfo.Mode()) | |
if err != nil { | |
return err | |
} | |
directory, _ := os.Open(source) | |
objects, err := directory.Readdir(-1) | |
for _, obj := range objects { | |
sourcefilepointer := source + "/" + obj.Name() | |
destinationfilepointer := dest + "/" + obj.Name() | |
if obj.IsDir() { | |
err = copy_folder(sourcefilepointer, destinationfilepointer) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} else { | |
err = copy_file(sourcefilepointer, destinationfilepointer) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} | |
} | |
return | |
} | |
func copy_file(source string, dest string) (err error) { | |
sourcefile, err := os.Open(source) | |
if err != nil { | |
return err | |
} | |
defer sourcefile.Close() | |
destfile, err := os.Create(dest) | |
if err != nil { | |
return err | |
} | |
defer destfile.Close() | |
_, err = io.Copy(destfile, sourcefile) | |
if err == nil { | |
sourceinfo, err := os.Stat(source) | |
if err != nil { | |
err = os.Chmod(dest, sourceinfo.Mode()) | |
} | |
} | |
return | |
} |
Here is a clean implementation: https://gist.github.com/m4ng0squ4sh/92462b38df26839a3ca324697c8cba04
@rol1 That link is now broken.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And don't use fmt.Println! Return the error!