чтение файла

This commit is contained in:
badkaktus 2019-10-11 13:42:25 +03:00
parent 186892989f
commit 46671879fc
3 changed files with 32 additions and 30 deletions

View File

@ -55,7 +55,7 @@ Epoch
Парсинг URL (URL Parsing) Парсинг URL (URL Parsing)
Хеш SHA1 (SHA1 Hashes) Хеш SHA1 (SHA1 Hashes)
Кодирование Base64 (Base64 Encoding) Кодирование Base64 (Base64 Encoding)
Reading Files Чтение файлов (Reading Files)
Writing Files Writing Files
Line Filters Line Filters
File Paths File Paths

View File

@ -1,6 +1,6 @@
// Reading and writing files are basic tasks needed for // Чтение и запись файлов это базовая задача, необходимая
// many Go programs. First we'll look at some examples of // для решения множества задач. Для начала мы рассмотрим
// reading files. // несколько примеров чтения файлов.
package main package main
@ -12,8 +12,9 @@ import (
"os" "os"
) )
// Reading files requires checking most calls for errors. // Чтение файлов требует проверок множества вызовов на
// This helper will streamline our error checks below. // наличие ошибок. Эта функция-хелпер поможет нам
// обрабатывать ошибки в одном месте.
func check(e error) { func check(e error) {
if e != nil { if e != nil {
panic(e) panic(e)
@ -22,28 +23,29 @@ func check(e error) {
func main() { func main() {
// Perhaps the most basic file reading task is // Возможно, самая основная задача чтения файлов -
// slurping a file's entire contents into memory. // это сохранение всего содержимого файла в памяти.
dat, err := ioutil.ReadFile("/tmp/dat") dat, err := ioutil.ReadFile("/tmp/dat")
check(err) check(err)
fmt.Print(string(dat)) fmt.Print(string(dat))
// You'll often want more control over how and what // Вам часто может потребоваться больший контроль
// parts of a file are read. For these tasks, start // над тем, как и какие части файла читаются. Для
// by `Open`ing a file to obtain an `os.File` value. // решения этих задач начните с открытия файла,
// чтобы получить значение `os.File`..
f, err := os.Open("/tmp/dat") f, err := os.Open("/tmp/dat")
check(err) check(err)
// Read some bytes from the beginning of the file. // Прочитаем несколько байт с начала файла. Будет
// Allow up to 5 to be read but also note how many // прочитано первые 5 байт, но также выведем,
// actually were read. // сколько фактически было прочитано.
b1 := make([]byte, 5) b1 := make([]byte, 5)
n1, err := f.Read(b1) n1, err := f.Read(b1)
check(err) check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1])) fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
// You can also `Seek` to a known location in the file // Вы так же можете получить конкретное место файла
// and `Read` from there. // с помощью `Seek` и выполнить `Read` оттуда.
o2, err := f.Seek(6, 0) o2, err := f.Seek(6, 0)
check(err) check(err)
b2 := make([]byte, 2) b2 := make([]byte, 2)
@ -52,10 +54,10 @@ func main() {
fmt.Printf("%d bytes @ %d: ", n2, o2) fmt.Printf("%d bytes @ %d: ", n2, o2)
fmt.Printf("%v\n", string(b2[:n2])) fmt.Printf("%v\n", string(b2[:n2]))
// The `io` package provides some functions that may // Пакет `io` предоставляет некоторые функции, которые
// be helpful for file reading. For example, reads // могут быть полезны для чтения файлов. Например,
// like the ones above can be more robustly // чтение, подобное приведенному выше, может быть
// implemented with `ReadAtLeast`. // более надежно реализовано с помощью `ReadAtLeast`.
o3, err := f.Seek(6, 0) o3, err := f.Seek(6, 0)
check(err) check(err)
b3 := make([]byte, 2) b3 := make([]byte, 2)
@ -63,22 +65,22 @@ func main() {
check(err) check(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3)) fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
// There is no built-in rewind, but `Seek(0, 0)` // Тут нет встроенной перемотки назад, но можно
// accomplishes this. // использовать `Seek(0, 0)` для этого.
_, err = f.Seek(0, 0) _, err = f.Seek(0, 0)
check(err) check(err)
// The `bufio` package implements a buffered // В пакете `bufio` реализован буферизованный ридер,
// reader that may be useful both for its efficiency // который может быть полезен из-за своей эффективности
// with many small reads and because of the additional // при большом количестве небольших операций чтения, и
// reading methods it provides. // из-за наличия дополнительных методов чтения, которые
// он предоставляет.
r4 := bufio.NewReader(f) r4 := bufio.NewReader(f)
b4, err := r4.Peek(5) b4, err := r4.Peek(5)
check(err) check(err)
fmt.Printf("5 bytes: %s\n", string(b4)) fmt.Printf("5 bytes: %s\n", string(b4))
// Close the file when you're done (usually this would // Закройте файл, когда вы закончите использовать его
// be scheduled immediately after `Open`ing with // (обычно закрытие с `defer`'ом делается сразу после открытия).
// `defer`).
f.Close() f.Close()
} }

View File

@ -8,4 +8,4 @@ go
2 bytes @ 6: go 2 bytes @ 6: go
5 bytes: hello 5 bytes: hello
# Next we'll look at writing files. # Далее рассмотрим запись в файл.