-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path18_file_block_copy.go
More file actions
87 lines (75 loc) · 1.81 KB
/
18_file_block_copy.go
File metadata and controls
87 lines (75 loc) · 1.81 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Dvacátá druhá část
// Vstupně-výstupní funkce standardní knihovny programovacího jazyka Go
// https://www.root.cz/clanky/vstupne-vystupni-funkce-standardni-knihovny-programovaciho-jazyka-go/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů z dvacáté druhé části:
// https://github.com/tisnik/go-root/blob/master/article_22/README.md
//
// Demonstrační příklad číslo 18:
// Blokové přenosy dat při kopii souboru.
package main
import (
"fmt"
"io"
"os"
)
func closeFile(file *os.File) {
fmt.Printf("Closing file '%s'\n", file.Name())
file.Close()
}
func copyFile(srcName, dstName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
panic(err)
}
defer closeFile(src)
dst, err := os.Create(dstName)
if err != nil {
panic(err)
}
defer closeFile(dst)
buffer := make([]byte, 16)
copied := int64(0)
for {
read, err := src.Read(buffer)
if read > 0 {
fmt.Printf("read %d bytes\n", read)
written, err := dst.Write(buffer[:read])
if written > 0 {
fmt.Printf("written %d bytes\n", written)
}
if err != nil {
fmt.Printf("write error %v\n", err)
return copied, err
}
copied += int64(written)
}
if err == io.EOF {
fmt.Println("reached end of file")
break
}
if err != nil {
fmt.Printf("other error %v\n", err)
return copied, err
}
}
return copied, nil
}
func testCopyFile(srcName, dstName string) {
copied, err := copyFile(srcName, dstName)
if err != nil {
fmt.Printf("copyFile('%s', '%s') failed!!!\n", srcName, dstName)
} else {
fmt.Printf("Copied %d bytes\n", copied)
}
fmt.Println()
}
func main() {
testCopyFile("test_input.txt", "output.txt")
}