Sling Academy
Home/Golang/How to copy or move a file in Go

How to copy or move a file in Go

Last updated: November 26, 2024

Go, also known as Golang, is a statically typed, compiled programming language designed by Google. It is known for its simplicity and efficient management of dependencies. Copying or moving files in Go can be achieved using the built-in "os" and "io" packages.

Copying a File

To copy a file in Go, you need to open both the source and destination files and use a buffer to read and write the data. Here is a step-by-step guide on how to accomplish this.


package main

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

func CopyFile(src, dst string) error {
    sourceFile, err := os.Open(src)
    if err != nil {
        return err
    }
    defer sourceFile.Close()

    destinationFile, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer destinationFile.Close()

    _, err = io.Copy(destinationFile, sourceFile)
    if err != nil {
        return err
    }

    return nil
}

func main() {
    src := "source.txt"
    dst := "destination.txt"

    err := CopyFile(src, dst)
    if err != nil {
        log.Fatalf("File copy failed: %v", err)
    }
    log.Println("File copied successfully!")
}

In this example, we use os.Open to open the source file and os.Create to create the destination file. The io.Copy function is then used to buffer the data from the source to the destination file. Don't forget to handle errors and defer the closure of files to clean up resources.

Moving a File

To move a file, you can use the os.Rename function, which effectively changes the file's path.


package main

import (
    "os"
    "log"
)

func MoveFile(src, dst string) error {
    err := os.Rename(src, dst)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    src := "source.txt"
    dst := "new_location/destination.txt"

    err := MoveFile(src, dst)
    if err != nil {
        log.Fatalf("File move failed: %v", err)
    }
    log.Println("File moved successfully!")
}

Here, os.Rename moves the file from the source path to the destination path. This function works well for renaming files or moving them across directories within the same file system. However, be cautious when moving between different physical drives as it might fail in such cases.

By using both CopyFile and MoveFile functions, you can manage files efficiently in Go.

Next Article: How to automatically generate unique file names in Go

Previous Article: How to get the current directory in Go

Series: File I/O and Operating System Interaction

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant