Reading and writing
Reading and writing files can be done in numerous ways. Go provides interfaces that make it easy to write your own functions that work with files or any other reader/writer interface.
Between the os
, io
, and ioutil
packages, you can find the right function for your needs. These examples cover a number of the options available.
Copying a file
The following example uses the io.Copy()
function to copy the contents from one reader to another writer:
package main import ( "io" "log" "os" ) func main() { // Open original file originalFile, err := os.Open("test.txt") if err != nil { log.Fatal(err) } defer originalFile.Close() // Create new file newFile, err := os.Create("test_copy.txt") if err != nil { log.Fatal(err) } defer newFile.Close() // Copy the bytes to destination from source bytesWritten, err := io.Copy(newFile, originalFile) if err != nil { log.Fatal(err) } log.Printf...