From 4389560fcee49b68cb8fe3d9f45ef2137256f32c Mon Sep 17 00:00:00 2001 From: datalore Date: Thu, 3 Oct 2024 10:51:39 +0200 Subject: [PATCH] change(io): Moved I/O to different file --- io.go | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ main.go | 41 ++--------------------------------------- 2 files changed, 58 insertions(+), 39 deletions(-) create mode 100644 io.go diff --git a/io.go b/io.go new file mode 100644 index 0000000..34c727f --- /dev/null +++ b/io.go @@ -0,0 +1,56 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "os" + "strconv" +) + +func loadPrimes() []int64 { + return loadPrimesTxt() +} + +func loadPrimesTxt() []int64 { + file, err := os.Open("prime.txt") + if err != nil { + log.Fatal(err) + } + + var primes []int64 + + scanner := bufio.NewScanner(file) + + for scanner.Scan() { + nextPrime, err := strconv.ParseInt(scanner.Text(), 10, 64) + if err != nil { + log.Fatal(err) + } + primes = append(primes, nextPrime) + } + + file.Close() + + return primes +} + +func writePrimes(primes []int64) { + writePrimesTxt(primes) +} + +func writePrimesTxt(primes []int64) { + file, err := os.Create("prime.txt") + if err != nil { + log.Fatal(err) + } + + writer := bufio.NewWriter(file) + + for _, prime := range primes { + writer.WriteString(fmt.Sprintf("%d\n", prime)) + } + + writer.Flush() + file.Close() +} diff --git a/main.go b/main.go index 4bb4cf8..2e92787 100644 --- a/main.go +++ b/main.go @@ -1,15 +1,14 @@ package main import ( - "bufio" "context" "flag" "fmt" "log" - "os" "runtime" "strconv" "time" + "os" ) func calculateProgress(start, end, step, index int64) float32 { @@ -194,20 +193,7 @@ func main() { func onlyGenerate(number int64, dontLoad bool, numRoutines int, useTensors bool) { primes := generatePrimes(number, !dontLoad, numRoutines, useTensors) - - file, err := os.Create("prime.txt") - if err != nil { - log.Fatal(err) - } - - writer := bufio.NewWriter(file) - - for _, prime := range primes { - writer.WriteString(fmt.Sprintf("%d\n", prime)) - } - - writer.Flush() - file.Close() + writePrimes(primes) } func calculate(number int64, dontLoad bool, numRoutines int, useTensors bool) { @@ -229,26 +215,3 @@ func calculate(number int64, dontLoad bool, numRoutines int, useTensors bool) { print(" = ") println(sum) } - -func loadPrimes() []int64 { - file, err := os.Open("prime.txt") - if err != nil { - log.Fatal(err) - } - - var primes []int64 - - scanner := bufio.NewScanner(file) - - for scanner.Scan() { - nextPrime, err := strconv.ParseInt(scanner.Text(), 10, 64) - if err != nil { - log.Fatal(err) - } - primes = append(primes, nextPrime) - } - - file.Close() - - return primes -}