change(io): Moved I/O to different file

This commit is contained in:
datalore 2024-10-03 10:51:39 +02:00
parent ac1a8b7039
commit 4389560fce
2 changed files with 58 additions and 39 deletions

56
io.go Normal file
View File

@ -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()
}

41
main.go
View File

@ -1,15 +1,14 @@
package main package main
import ( import (
"bufio"
"context" "context"
"flag" "flag"
"fmt" "fmt"
"log" "log"
"os"
"runtime" "runtime"
"strconv" "strconv"
"time" "time"
"os"
) )
func calculateProgress(start, end, step, index int64) float32 { func calculateProgress(start, end, step, index int64) float32 {
@ -194,20 +193,7 @@ func main() {
func onlyGenerate(number int64, dontLoad bool, numRoutines int, useTensors bool) { func onlyGenerate(number int64, dontLoad bool, numRoutines int, useTensors bool) {
primes := generatePrimes(number, !dontLoad, numRoutines, useTensors) primes := generatePrimes(number, !dontLoad, numRoutines, useTensors)
writePrimes(primes)
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()
} }
func calculate(number int64, dontLoad bool, numRoutines int, useTensors bool) { 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(" = ") print(" = ")
println(sum) 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
}