95 lines
1.8 KiB
Go
95 lines
1.8 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
// Формирует файл /var/result/data.txt так,
|
||
|
// что каждая строка файла - количество символов в именах файлов из каталога /var/data.
|
||
|
|
||
|
const INPUT = "/var/data"
|
||
|
const OUTPUT = "/data/result"
|
||
|
|
||
|
func GetListFilesInDirectory(directory string) ([]string, error) {
|
||
|
f, err := os.Open(directory)
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
return nil, err
|
||
|
}
|
||
|
files, err := f.Readdir(0)
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
var fileNames []string
|
||
|
for _, file := range files {
|
||
|
fileName := file.Name()
|
||
|
fileNames = append(fileNames, fileName)
|
||
|
}
|
||
|
return fileNames, nil
|
||
|
}
|
||
|
|
||
|
func Exists(name string) (bool, error) {
|
||
|
_, err := os.Stat(name)
|
||
|
if os.IsNotExist(err) {
|
||
|
return false, nil
|
||
|
}
|
||
|
return err != nil, err
|
||
|
}
|
||
|
|
||
|
func CreateFileOrOpenIfExist(name string) (*os.File, error) {
|
||
|
exists, err := Exists(name)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
if exists {
|
||
|
return os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0664)
|
||
|
}
|
||
|
return os.Create(name)
|
||
|
}
|
||
|
|
||
|
func CreateFileAndWriteData(filename string, lines []string) error {
|
||
|
file, err := CreateFileOrOpenIfExist(filename)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
for _, line := range lines {
|
||
|
_, err = fmt.Fprintf(file, line)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
err = file.Close()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
filenames, err := GetListFilesInDirectory(INPUT)
|
||
|
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
var lenghtOfFilenames []string
|
||
|
for _, filename := range filenames {
|
||
|
fmt.Println(filename)
|
||
|
lenghtOfFilenames = append(lenghtOfFilenames, fmt.Sprintf("%d", len(filename)))
|
||
|
}
|
||
|
|
||
|
err = CreateFileAndWriteData(OUTPUT+"/data.txt", filenames)
|
||
|
if err != nil {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
fmt.Println("First Service is end.")
|
||
|
}
|