My goal is to check all the lines of the file (there is one word per line) and if the string is not present in the whole file, I have to add it at the bottom.
The problem is that the "is_Cursor" loop changes my "tx.Data" and therefore I have to give the for loop several times and start again several times from the beginning
fileWrite, err := os.OpenFile(fileName, os.O_APPEND|os.O_RDWR, os.ModeAppend)
if err != nil {
log.Fatalln(err)
}
defer fileWrite.Close()
fileRead, err := os.Open(fileName)
if err != nil {
log.Fatalln(err)
}
defer fileRead.Close()
isWrite := false
for is_Cursor {
for i := 0; i < len(tx.Data) && i < maxMemoryTx; i++ {
isWrite = false
//scannerWrite := bufio.NewScanner(fileWrite)
scannerRead := bufio.NewScanner(fileRead)
for scannerRead.Scan() {
fmt.Println(scannerRead.Text())
if scannerRead.Text() == tx.Data[i].Type {
println("block")
isWrite = true
}
}
if !isWrite {
if scannerRead.Scan() == false {
println("new")
fileWrite.WriteString(tx.Data[i].Type)
}
if _, err := fileWrite.WriteString("\n"); err != nil {
log.Fatal(err)
}
}
}
//other
}
Where am I doing wrong?
how do i check and then insert in the file if necessary?
check all the lines of the file (there is one word per line) and if the string is not present in the whole file, I have to add it at the bottom.
Follow the instructions. Read all the words in the file. Then, add any new words at the end. For example,
func appendNewWords(fileName string, newWords []string) error {
fileWords := make(map[string]bool)
file, err := os.OpenFile(fileName, os.O_APPEND|os.O_RDWR, os.ModeAppend)
if err != nil {
return err
}
defer file.Close()
scnr := bufio.NewScanner(file)
for scnr.Scan() {
fileWords[scnr.Text()] = true
}
if err := scnr.Err(); err != nil {
return err
}
wtr := bufio.NewWriter(file)
for _, word := range newWords {
if !fileWords[word] {
fileWords[word] = true
_, err := wtr.WriteString(word)
if err != nil {
return err
}
err = wtr.WriteByte('\n')
if err != nil {
return err
}
}
}
err = wtr.Flush()
if err != nil {
return err
}
err = file.Close()
if err != nil {
return err
}
return nil
}