временные файлы и каталоги

This commit is contained in:
badkaktus 2019-10-11 15:52:26 +03:00
parent d41d978a14
commit 4d63d4ae43
2 changed files with 28 additions and 29 deletions

View File

@ -60,7 +60,7 @@ Epoch
Строковые фильтры (Line Filters) Строковые фильтры (Line Filters)
Пути к файлам (File Paths) Пути к файлам (File Paths)
Директории (Directories) Директории (Directories)
Temporary Files and Directories Временные файлы и директории (Temporary Files and Directories)
Testing Testing
Command-Line Arguments Command-Line Arguments
Command-Line Flags Command-Line Flags

View File

@ -1,8 +1,8 @@
// Throughout program execution, we often want to create // Во время выполнения программы мы часто хотим создавать
// data that isn't needed after the program exits. // данные, которые не нужны после выхода из программы.
// *Temporary files and directories* are useful for this // *Временные файлы и каталоги* полезны для этой цели,
// purpose since they don't pollute the file system over // поскольку они не загрязняют файловую систему с
// time. // течением времени.
package main package main
@ -21,44 +21,43 @@ func check(e error) {
func main() { func main() {
// The easiest way to create a temporary file is by // Простейший способ создания временного файла - это
// calling `ioutil.TempFile`. It creates a file *and* // вызов `ioutil.TempFile`. Он создаст *и* откроет
// opens it for reading and writing. We provide `""` // файл для чтения и записи. Мы использовали `""` в
// as the first argument, so `ioutil.TempFile` will // качестве первого аргумента, и поэтому `ioutil.TempFile`
// create the file in the default location for our OS. // создаст файл в директории по-умолчанию.
f, err := ioutil.TempFile("", "sample") f, err := ioutil.TempFile("", "sample")
check(err) check(err)
// Display the name of the temporary file. On // Показать имя временного файла. В ОС на основе Unix
// Unix-based OSes the directory will likely be `/tmp`. // каталог, вероятно, будет `/tmp`. Имя файла начинается
// The file name starts with the prefix given as the // с префикса, заданного в качестве второго аргумента
// second argument to `ioutil.TempFile` and the rest // `ioutil.TempFile`, а остальное выбирается автоматически,
// is chosen automatically to ensure that concurrent // чтобы параллельные вызовы всегда создавали разные
// calls will always create different file names. // имена файлов.
fmt.Println("Temp file name:", f.Name()) fmt.Println("Temp file name:", f.Name())
// Clean up the file after we're done. The OS is // Удалите файл после того, как мы закончим. Через
// likely to clean up temporary files by itself after // некоторое время ОС, скорее всего, сама очистит
// some time, but it's good practice to do this // временные файлы, но рекомендуется делать это явно.
// explicitly.
defer os.Remove(f.Name()) defer os.Remove(f.Name())
// We can write some data to the file. // Мы можем записать какую-то информацию в файл.
_, err = f.Write([]byte{1, 2, 3, 4}) _, err = f.Write([]byte{1, 2, 3, 4})
check(err) check(err)
// If we intend to write many temporary files, we may // Если мы намереваемся написать много временных файлов,
// prefer to create a temporary *directory*. // мы можем предпочесть создать *временный каталог*. Аргументы
// `ioutil.TempDir`'s arguments are the same as // `ioutil.TempDir` совпадают с аргументами `TempFile`,
// `TempFile`'s, but it returns a directory *name* // но он возвращает *имя каталога*, а не открытый файл.
// rather than an open file.
dname, err := ioutil.TempDir("", "sampledir") dname, err := ioutil.TempDir("", "sampledir")
fmt.Println("Temp dir name:", dname) fmt.Println("Temp dir name:", dname)
defer os.RemoveAll(dname) defer os.RemoveAll(dname)
// Now we can synthesize temporary file names by // Теперь мы можем синтезировать временные имена
// prefixing them with our temporary directory. // файлов, добавив к ним префикс нашего
// временного каталога.
fname := filepath.Join(dname, "file1") fname := filepath.Join(dname, "file1")
err = ioutil.WriteFile(fname, []byte{1, 2}, 0666) err = ioutil.WriteFile(fname, []byte{1, 2}, 0666)
check(err) check(err)