File handling in Go

 File handling in Go


Go has built-in support for reading and writing files.


The os package provides functions for opening, closing, reading, and writing files.



f, err := os.Create("data.txt")

if err != nil {

    // handle the error

}

defer f.Close()


_, err = f.WriteString("Hello, world!\n")

if err != nil {

    // handle the error

}


data := make([]byte, 100)

n, err := f.Read(data)

if err != nil {

    // handle the error

}

fmt.Println(string(data[:n])) // prints Hello, world!

In this example, we create a new file called data.txt by using the os.Create() function. We write a string to the file by using the f.WriteString() function, and we read the contents of the file into a byte slice by using the f.Read() function.


We also use the defer keyword to ensure that the file is closed when the function returns, regardless of whether an error occurred.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...