/
io.go
67 lines (60 loc) · 1.29 KB
/
io.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2018, Shulhan <ms@kilabit.info>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Package io provide a library for reading and watching file, and reading
// from standard input.
//
package io
import (
"fmt"
"io"
"log"
"os"
)
//
// Copy file from in to out.
// If the output file is already exist, it will be truncated.
// If the file is not exist, it will created with permission set to user's
// read-write only.
//
func Copy(out, in string) (err error) {
fin, err := os.Open(in)
if err != nil {
return fmt.Errorf("Copy: failed to open input file: %s", err)
}
fout, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("Copy: failed to open output file: %s", err)
}
defer func() {
err := fout.Close()
if err != nil {
log.Printf("Copy: failed to close output file: %s", err)
}
}()
defer func() {
err := fin.Close()
if err != nil {
log.Printf("Copy: failed to close input file: %s", err)
}
}()
buf := make([]byte, 1024)
for {
n, err := fin.Read(buf)
if err != nil {
if err == io.EOF {
break
}
return err
}
if n == 0 {
break
}
_, err = fout.Write(buf[:n])
if err != nil {
return err
}
}
return nil
}