From 46671879fc635e1c670d5bafdf6d3fbcd1e018e4 Mon Sep 17 00:00:00 2001 From: badkaktus Date: Fri, 11 Oct 2019 13:42:25 +0300 Subject: [PATCH] =?UTF-8?q?=D1=87=D1=82=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=84?= =?UTF-8?q?=D0=B0=D0=B9=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples.txt | 2 +- examples/reading-files/reading-files.go | 58 +++++++++++++------------ examples/reading-files/reading-files.sh | 2 +- 3 files changed, 32 insertions(+), 30 deletions(-) diff --git a/examples.txt b/examples.txt index 9ee0f45..aec318d 100644 --- a/examples.txt +++ b/examples.txt @@ -55,7 +55,7 @@ Epoch Парсинг URL (URL Parsing) Хеш SHA1 (SHA1 Hashes) Кодирование Base64 (Base64 Encoding) -Reading Files +Чтение файлов (Reading Files) Writing Files Line Filters File Paths diff --git a/examples/reading-files/reading-files.go b/examples/reading-files/reading-files.go index 49387a6..4b7b89b 100644 --- a/examples/reading-files/reading-files.go +++ b/examples/reading-files/reading-files.go @@ -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 @@ -12,8 +12,9 @@ import ( "os" ) -// Reading files requires checking most calls for errors. -// This helper will streamline our error checks below. +// Чтение файлов требует проверок множества вызовов на +// наличие ошибок. Эта функция-хелпер поможет нам +// обрабатывать ошибки в одном месте. func check(e error) { if e != nil { panic(e) @@ -22,28 +23,29 @@ func check(e error) { func main() { - // Perhaps the most basic file reading task is - // slurping a file's entire contents into memory. + // Возможно, самая основная задача чтения файлов - + // это сохранение всего содержимого файла в памяти. dat, err := ioutil.ReadFile("/tmp/dat") check(err) 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") check(err) - // Read some bytes from the beginning of the file. - // Allow up to 5 to be read but also note how many - // actually were read. + // Прочитаем несколько байт с начала файла. Будет + // прочитано первые 5 байт, но также выведем, + // сколько фактически было прочитано. b1 := make([]byte, 5) n1, err := f.Read(b1) check(err) 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) check(err) b2 := make([]byte, 2) @@ -52,10 +54,10 @@ func main() { fmt.Printf("%d bytes @ %d: ", n2, o2) fmt.Printf("%v\n", string(b2[:n2])) - // The `io` package provides some functions that may - // be helpful for file reading. For example, reads - // like the ones above can be more robustly - // implemented with `ReadAtLeast`. + // Пакет `io` предоставляет некоторые функции, которые + // могут быть полезны для чтения файлов. Например, + // чтение, подобное приведенному выше, может быть + // более надежно реализовано с помощью `ReadAtLeast`. o3, err := f.Seek(6, 0) check(err) b3 := make([]byte, 2) @@ -63,22 +65,22 @@ func main() { check(err) 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) check(err) - // The `bufio` package implements a buffered - // reader that may be useful both for its efficiency - // with many small reads and because of the additional - // reading methods it provides. + // В пакете `bufio` реализован буферизованный ридер, + // который может быть полезен из-за своей эффективности + // при большом количестве небольших операций чтения, и + // из-за наличия дополнительных методов чтения, которые + // он предоставляет. r4 := bufio.NewReader(f) b4, err := r4.Peek(5) check(err) 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() } diff --git a/examples/reading-files/reading-files.sh b/examples/reading-files/reading-files.sh index a1deb72..cd234c3 100644 --- a/examples/reading-files/reading-files.sh +++ b/examples/reading-files/reading-files.sh @@ -8,4 +8,4 @@ go 2 bytes @ 6: go 5 bytes: hello -# Next we'll look at writing files. +# Далее рассмотрим запись в файл.