Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Make a copy of a file in Go (Golang)

Posted on April 16, 2020April 16, 2020 by admin

In this article we will see two methods of copying a file.

Table of Contents

  • First Method
  • Second Method

First Method

io.Copy() can be used to create a copy of the file from src to dest. A successful copy will return err != nil instead of err == EOF

Below is the signature of the function. It returns the number of bytes written to the dest

func Copy(dst Writer, src Reader) (written int64, err error)

Code

First create a file named “original.txt” and write some content in it.

package main

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

// Copy a file
func main() {
    // Open original file
    original, err := os.Open("original.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer original.Close()

    // Create new file
    new, err := os.Create("new.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer new.Close()

    //This will copy
    bytesWritten, err := io.Copy(new, original)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Bytes Written: %d\n", bytesWritten)
}

Output:

Bytes Written: 

Second Method

If the contents of the file is less then we can also read the contents of the file first and then write all the contents to the new file. See below code.

Here also first create a file named “original.txt” and write some content in it

package main
import (
    "io/ioutil"
    "log"
)

// Copy a file
func main() {
    //Read all the contents of the  original file
    bytesRead, err := ioutil.ReadFile("original.txt")
    if err != nil {
        log.Fatal(err)
    }

    //Copy all the contents to the desitination file
    err = ioutil.WriteFile("new.txt", bytesRead, 0755)
    if err != nil {
        log.Fatal(err)
    }
}

Output

new.txt file will have same content as original.txt
  • copy
  • file
  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme