запись файлов

This commit is contained in:
badkaktus 2019-10-11 13:50:19 +03:00
parent 46671879fc
commit 3e4828bcb4
3 changed files with 23 additions and 19 deletions

View File

@ -56,7 +56,7 @@ Epoch
Хеш SHA1 (SHA1 Hashes)
Кодирование Base64 (Base64 Encoding)
Чтение файлов (Reading Files)
Writing Files
Запись файлов (Writing Files)
Line Filters
File Paths
Directories

View File

@ -1,5 +1,5 @@
// Writing files in Go follows similar patterns to the
// ones we saw earlier for reading.
// Запись файло в Go следует тем же шаблонам, что мы
// видели ранее в главе "`Чтение`".
package main
@ -18,41 +18,44 @@ func check(e error) {
func main() {
// To start, here's how to dump a string (or just
// bytes) into a file.
// В этом примере показано вот как записать строку
// (или только байты) в файл.
d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("/tmp/dat1", d1, 0644)
check(err)
// For more granular writes, open a file for writing.
// Для более детальной записи откройте файл для записи.
f, err := os.Create("/tmp/dat2")
check(err)
// It's idiomatic to defer a `Close` immediately
// after opening a file.
// Идиоматично откладывать `закрытие` с помощью `defer`'a
// сразу после открытия файла.
defer f.Close()
// You can `Write` byte slices as you'd expect.
// Вы можете `записать` срез байт, как и ожидается.
d2 := []byte{115, 111, 109, 101, 10}
n2, err := f.Write(d2)
check(err)
fmt.Printf("wrote %d bytes\n", n2)
// A `WriteString` is also available.
// Запись строки `WriteString` так же доступна.
n3, err := f.WriteString("writes\n")
fmt.Printf("wrote %d bytes\n", n3)
// Issue a `Sync` to flush writes to stable storage.
// Выполните синхронизацию `Sync` для сброса записей
// в стабильное хранилище.
f.Sync()
// `bufio` provides buffered writers in addition
// to the buffered readers we saw earlier.
// `bufio` предоставляет буферизованных `писателей`
// в дополнение к буферизованным `читателям`, которые
// мы видели ранее.
w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
fmt.Printf("wrote %d bytes\n", n4)
// Use `Flush` to ensure all buffered operations have
// been applied to the underlying writer.
// Используйте `Flush`, чтобы убедиться, что все
// буферизованные операции были применены к основному
// модулю записи.
w.Flush()
}

View File

@ -1,10 +1,10 @@
# Try running the file-writing code.
# Пробуем запустить запись в файл.
$ go run writing-files.go
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
# Then check the contents of the written files.
# Потом проверим, что контент появился в файлах.
$ cat /tmp/dat1
hello
go
@ -13,5 +13,6 @@ some
writes
buffered
# Next we'll look at applying some of the file I/O ideas
# we've just seen to the `stdin` and `stdout` streams.
# Далее мы рассмотрим применение некоторых идей файлового
# ввода-вывода, которые мы только что видели, к потокам
# `stdin` и `stdout`.