Directories in Go

Go: Directories

In Go, the "os"package provides a way to manipulate files and directories. Here are some basic directory-related functions you can use:

1. os.Mkdir:

This function creates a new directory with the specified name and permissions. If the directory already exists, it returns an error.

  • Example:

    err := os.Mkdir("mydir", 0755)
    if err != nil {
        fmt.Println(err)
    }

2. os.MkdirAll:

This function creates a new directory and any necessary parent directories. If the directory already exists, it does nothing.

  • Example:

    err := os.MkdirAll("path/to/mydir", 0755)
    if err != nil {
        fmt.Println(err)
    }

3. os.Remove:

This function removes a file or empty directory with the specified name. If the file or directory doesn't exist, it returns an error.

  • Example:

    err := os.Remove("mydir")
    if err != nil {
        fmt.Println(err)
    }

4. os.RemoveAll:

This function removes a file or directory and any contents it may have. If the file or directory doesn't exist, it does nothing.

  • Example:

    err := os.RemoveAll("path/to/mydir")
    if err != nil {
        fmt.Println(err)
    }

5. os.Open:

This function opens a file with the specified name and mode. The mode can be used to control whether the file should be opened for reading, writing, or both. If the file doesn't exist, it returns an error.

  • Example:

    file, err := os.Open("myfile.txt")
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close() // always remember to close the file when done!

6. os.ReadDir:

This function returns a slice of os.DirEntry structs representing the files and subdirectories in the specified directory. Each os.DirEntry contains information about the file or directory, such as its name, size, and modification time.

  • Example:
    entries, err := os.ReadDir("path/to/mydir")
    if err != nil {
        fmt.Println(err)
    }
    for _, entry := range entries {
        fmt.Println(entry.Name(), entry.Size(), entry.ModTime())
    }

7. os.Stat:

This function returns an os.FileInfo struct containing information about the specified file or directory, such as its name, size, and modification time.

  • Example:
    info, err := os.Stat("myfile.txt")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(info.Name(), info.Size(), info.ModTime())

These are just some basic examples of how to use these functions. There are many more things you can do with files and directories in Go, so I encourage you to check out the official Go documentation for more details!

Next Article