Cookie Consent by Free Privacy Policy Generator 📌 Read and Write files in Golang


✅ Read and Write files in Golang


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

In this tutorial, we will learn how to read, write, and append to a file using Golang.

The built-in os package provides reading and writing files. Earlier it used to be handled by io/ioutil package.

A file must have correct file permissions to perform respective operations.

Following are the file modes(permissions) codes that we will need in the tutorial.

0000     no permissions
0700     read, write, & execute only for the owner
0770     read, write, & execute for owner and group
0777     read, write, & execute for owner, group and others
0111     execute
0222     write
0333     write & execute
0444     read
0555     read & execute
0666     read & write
0740     owner can read, write, & execute; group can only read; others have no permissions

Write file in golang

The os.Writefile function accepts the filename or full path with extension if any, data or content in []byte format and file permission code.

Syntax

func WriteFile(name string, data []byte, perm os.FileMode) error

The below code will create a new file if it doesn't exist and write or it will override with new content to the existing file.
The 0777 file mode gives read, write and execution permission.
The data is a string converted to []byte format.

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    data := []byte("dev.to")
    err := os.WriteFile("test.txt", data, 0777)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("file written successfully.")
}

Read file in golang

The os.ReadFile function accepts the filename or full file path and returns []byte and error.

It will throw an error if the file doesn't exist or the file doesn't have permission to read.

Syntax

func ReadFile(name string) ([]byte, error)
package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    data, err := os.ReadFile("test.txt")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(data))
}

Append to an existing file

There are 2 ways you can append content to an existing file.

1. Read and Write

In this approach, first read the file, append the content and then write the file.

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    data, err := os.ReadFile("test.txt")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(data))

    msg := []byte("\nappended message")

    data = append(data, msg...)

    err = os.WriteFile("test.txt", data, 0777)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("file written successfully.")
}

2. Open and write

In this approach, first, open the file with the O_APPEND flag then write the content and close the file.

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0777)
    if err != nil {
        log.Fatal(err)
    }

    defer file.Close()

    msg := []byte("\n another appended message")
    _, err = file.Write(msg)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("file appended successfully.")
}

os.O_APPEND - File permission append
os.O_CREATE - Create a new file if it doesn't exist
os.O_WRONLY - Write only

I hope you like this tutorial.
You can also watch this tutorial on YouTube.
Happy Coding. Please Follow and Subscribe to YouTube.

Read and Write files in Golang #golang - YouTube

In this short tutorial, you will learn how to read, write and append a file.Checkout✅ Golang developer Roadmap https://youtu.be/wJ6JP22YOUk✅ Run Goroutines i...

favicon youtube.com
...

✅ Read and Write files in Golang


📈 35.88 Punkte

✅ GitHub Security Lab: Golang : Improvements to Golang SSRF query


📈 24.94 Punkte

✅ How to use GoLang in Flutter Application - Golang FFI


📈 24.94 Punkte

✅ GoLang JWT Authentication Using Golang Gin Framework with MongoDB


📈 24.94 Punkte

✅ How to Read and Write Files with C# FileStream


📈 23.4 Punkte

✅ Leveraging PostGIS to Write And Read FlatGeobuf Files


📈 23.4 Punkte

✅ CVE-2020-14125 | Xiaomi Redmi Note 9T/Redmi Note 11 read/write out-of-bounds write


📈 22.9 Punkte

✅ CVE-2023-28445 | Deno 1.32.0 Asynchronous Operation read/write out-of-bounds write (GHSA-c25x-cm9x-qqgx)


📈 22.9 Punkte

✅ Privilege Escalation Flaw in Cisco ASA Allows Attackers To Read or Write Files in the System


📈 21.87 Punkte

✅ Privilege Escalation Flaw in Cisco ASA Allows Attackers To Read or Write Files in the System


📈 21.87 Punkte

✅ You can write to OneDrive files with the iOS Files app again


📈 21.06 Punkte

✅ Write a Simple blockchain in Golang


📈 20.17 Punkte

✅ How to Write Data to InfluxDB v3 with GoLang: A Step-by-Step Tutorial


📈 20.17 Punkte

✅ Read JSON file in GoLang (Unstructured Data)


📈 19.96 Punkte

✅ Read csv file using Golang


📈 19.96 Punkte

✅ nao1215/csv - Read csv with validation in golang


📈 19.96 Punkte

✅ Read data from channel Golang


📈 19.96 Punkte

✅ Tricky Golang interview questions - Part 6: NonBlocking Read


📈 19.96 Punkte

✅ Snake Ransomware That Written in Golang Language Removes Backup Shadows Copies & Encrypt Windows Files


📈 19.15 Punkte

✅ Vuln: Foxit Reader and Foxit PhantomPDF Out of Bounds Read and Write Remote Code Execution Vulnerability


📈 18.26 Punkte

✅ Vuln: Foxit Reader and Foxit PhantomPDF Out of Bounds Read and Write Remote Code Execution Vulnerability


📈 18.26 Punkte

✅ How to access and READ stdin and stdout system files


📈 17.24 Punkte

✅ Vuln: LibTIFF CVE-2014-8129 Out of Bounds Read and Write Multiple Remote Denial of Service Vulnerabilities


📈 16.73 Punkte

✅ Vuln: LibTIFF CVE-2014-8129 Out of Bounds Read and Write Multiple Remote Denial of Service Vulnerabilities


📈 16.73 Punkte

✅ Vuln: QEMU CVE-2017-11334 Out of Bounds Read and Write Denial of Service Vulnerability


📈 16.73 Punkte

✅ Vuln: QEMU Out of Bounds Read and Write Memory Access CVE-2017-14167 Local Integer Overflow Vulnerability


📈 16.73 Punkte











matomo

Datei nicht gefunden!