-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles.go
94 lines (77 loc) · 2.19 KB
/
files.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//работа с файлами
//полезный источник https://golangbot.com/write-files/
//термин "файловый дескриптор" это собственно объект описывающий файл
//пример myFile, _ := os.OpenFile("testsFiles/file1.txt", os.O_APPEND|os.O_WRONLY, 0666)
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
)
func main() {
//скопировать содержание одного файла в другой файл
//copyFile("testsFiles/source.txt","testsFiles/destination.txt")
//считать файл построчно
//readFileLineByLine()
//запись в файл
//writeToFile()
/*запись вконец файла*/
appendToTheEndOfFile()
}
/*копирование одного файла в другой*/
func copyFile(src, dst string) (written int64, err error) {
//возвращает EOF - end of file, то есть количество символов по сути
//открытие файла
source, err := os.Open(src)
if err != nil {
fmt.Println("source open problem")
return
}
defer source.Close()
//создание или открытие другого файла
destination, err := os.Create(dst)
if err != nil {
fmt.Println("destination create problem")
return
}
defer destination.Close()
//копирование
written, err = io.Copy(destination, source)
if err != nil {
fmt.Println("copy problem")
}
fmt.Println(written)
return
}
/*чтение файла построчно*/
func readFileLineByLine() {
myFile, err := os.Open("testsFiles/socks.txt")
if err != nil {
log.Fatal(err)
}
defer myFile.Close()
scanner := bufio.NewScanner(myFile)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
/*Запись в файл*/
func writeToFile() {
myFile, err := os.Create("testsFiles/file1.txt")
if err != nil {
log.Fatal(err)
}
defer myFile.Close()
writer, err := myFile.WriteString("mystring")
if err != nil {
log.Fatal("filed write ", err)
}
log.Println(writer)
}
func appendToTheEndOfFile() {
myFile, _ := os.OpenFile("testsFiles/file1.txt", os.O_APPEND|os.O_WRONLY, 0666)
defer myFile.Close()
fmt.Fprintf(myFile, "Sting number two")
}