Beispiele in GoLang#
Interpretieren: go run <file> Kompilieren: go build <file>
read file, modify it and write it back (28.12.2021)#
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)#
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
Add new attachment
Only authorized users are allowed to upload new attachments.