DAS_2024_1/bazunov_andrew_lab_2/FileCreator/main.go
Bazunov Andrew Igorevich eeac04be49 Complete lab 2
2024-10-02 17:58:40 +04:00

93 lines
1.6 KiB
Go

package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"math/rand"
"os"
"path/filepath"
)
const DIR = "/var/data"
func Exists(name string) (bool, error) {
_, err := os.Stat(name)
if os.IsNotExist(err) {
return false, nil
}
return err != nil, err
}
func CreateDirectory(dirs string) error {
if _, err := os.Stat(dirs); os.IsNotExist(err) {
err := os.MkdirAll(dirs, 0664)
if err != nil {
return err
}
}
return nil
}
func CreateFileOrOpenIfExist(name string) (*os.File, error) {
err := CreateDirectory(filepath.Dir(name))
if err != nil {
return nil, err
}
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) error {
file, err := CreateFileOrOpenIfExist(filename)
if err != nil {
return err
}
lines := rand.Intn(1000) + 100
for i := 0; i < lines; i++ {
randomValueForLine := rand.Intn(1_000_000)
_, err = fmt.Fprintf(file, "%d\r\n", randomValueForLine)
if err != nil {
return err
}
}
err = file.Close()
if err != nil {
return err
}
return nil
}
func GetMD5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
func main() {
for i := 0; i < 10; i++ {
filename := fmt.Sprintf("%s/%s.txt", DIR, GetMD5Hash(fmt.Sprintf("%d", i)))
err := CreateFileAndWriteData(filename)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("Created file %s\n", filename)
}
}
err := CreateFileAndWriteData(DIR + "/data.txt")
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("Created file %s\n", DIR+"/data.txt")
}
}