tech:go_lang_-_les_fichiers
Go lang - les fichiers
Exemple lecture fichier texte
package main import ( "bufio" "fmt" "os" ) func main() { file, err := os.Open("input.txt") if err != nil { panic(err) } defer func() { if err := file.Close(); err != nil { panic(err) } }() scanner := bufio.NewScanner(file) // Iterate over each line for scanner.Scan() { line := scanner.Text() fmt.Println(line) } }
Exemple d'écriture texte
func write_file(filename string, data string) { file, err := os.Create(filename) if err != nil { panic(err) } defer func() { if err := file.Close(); err != nil { panic(err) } }() _, err = file.WriteString(data) if err != nil { panic(err) } }
Exemple de copie de fichier
Voir : https://opensource.com/article/18/6/copying-files-go
func copyFile(src, dest string) { input, err := ioutil.ReadFile(src) if err != nil { panic(err) } err = ioutil.WriteFile(dest, input, 0644) if err != nil { fmt.Println("Error creating", dest) panic(err) } }
Fichier droits POSIX octal mode
Voir aussi :
file, err := os.Lstat("/tmp/plop") if err != nil { panic(err) } mode := file.Mode() fmt.Printf("%s\n", mode) fmt.Printf("%o\n", mode)
Exemple lecture fichier CSV
package main import ( "encoding/csv" "fmt" "log" "os" "regexp" ) func IsMatchingRegex(s string, regex string) bool { return regexp.MustCompile(regex).MatchString(s) } func main() { file, err := os.Open("data.csv") if err != nil { log.Fatal(err) } defer file.Close() // Read all records from the CSV file reader := csv.NewReader(file) reader.Comma = ';' records, err := reader.ReadAll() if err != nil { log.Fatal(err) } for _, record := range records[1:] { if IsMatchingRegex(record[0], "^#") { continue } fmt.Println(record[0]) fmt.Println(record[1]) } }
Exemple de calcul de hash d'un fichier
package main import ( "crypto/sha256" "encoding/hex" "fmt" "io" "os" ) func hashFile(filePath string) (string, error) { file, err := os.Open(filePath) if err != nil { return "", fmt.Errorf("failed to open file: %w", err) } defer file.Close() hasher := sha256.New() if _, err := io.Copy(hasher, file); err != nil { return "", fmt.Errorf("failed to hash file: %w", err) } return hex.EncodeToString(hasher.Sum(nil)), nil } func main() { hash, err := hashFile("/tmp/plop") if err != nil { panic(err) } fmt.Println(hash) }
tech/go_lang_-_les_fichiers.txt · Dernière modification : de Jean-Baptiste
