This page (revision-3) was last changed on 29-Dec-2021 08:21 by Markus Monderkamp 

This page was created on 28-Dec-2021 22:07 by Markus Monderkamp

Only authorized users are allowed to rename pages.

Only authorized users are allowed to delete pages.

Page revision history

Version Date Modified Size Author Changes ... Change note
3 29-Dec-2021 08:21 2 KB Markus Monderkamp to previous testfile.go
2 28-Dec-2021 22:07 1 KB Markus Monderkamp to previous | to last Datum ergänzt
1 28-Dec-2021 22:07 1 KB Markus Monderkamp to last Beispiele-Start mit Dateilesen, Modifizieren und Schreiben

Page References

Incoming links Outgoing links

Version management

Difference between version and

!Beispiele in GoLang

Interpretieren: go run <file>
Kompilieren: go build <file>

----

!!read file, modify it and write it back (28.12.2021)>>

%%prettify
{{{
package main

// filemodify.go - read file, modify it and write it back

/*cat testdata/hello
hello gopher
hello helmut
*/

// inspired by:
// https://pkg.go.dev/io/ioutil#example-ReadFile on 20211228
// and
// https://www.geeksforgeeks.org/strings-replace-function-in-golang-with-examples/

import (
       "fmt"
       "io/ioutil"
       "log"
       "strings"
)

func main() {
       content, err := ioutil.ReadFile("testdata/hello")
       if err != nil {  
               log.Fatal(err)
       }

       //https://yourbasic.org/golang/convert-string-to-byte-slice/
       //s := string([]byte{65, 66, 67, 226, 130, 172})
       contentstring := string(content)

       //strings.Replace(contentstring, "helmut", "hannelore", -1) // -1 replaces all
       contentmodifiedstring := strings.Replace(contentstring, "h", "g", 2)
       //strings.ReplaceAll(contentstring, "h", "g")

       fmt.Printf("File contents:\n%s", contentmodifiedstring)

       //b := []byte("ABC€")
       contentbyte := []byte(contentmodifiedstring)

       //func WriteFile(filename string, data []byte, perm fs.FileMode) error
       errwrite := ioutil.WriteFile("testdata/hellomodified", contentbyte, 0644)
       if err != nil {
               log.Fatal(errwrite)
       }

}

}}}
/%

----

<<!!Prüfung in testfile.go, ob Datei existiert (29.12.2021)
<<
%%prettify
{{{
package main

// testfile.go - test, ob Datei existiert
// Quelle: https://stackoverflow.com/questions/12518876/how-to-check-if-a-file-exists-in-go

import (
       "fmt"
"os"
"errors"
)


func main() {

filepath := string("D:/Benutzer/f003228/src/go/testfile/testfile")

if _, err := os.Stat(filepath); errors.Is(err, os.ErrNotExist) {
  // path/to/whatever does not exist
fmt.Printf("Datei %s existiert nicht\n", filepath)
} else {
  fmt.Printf("Datei %s existiert\n", filepath)
}
}
}}}
/%


----

Fin