» Quick Introduction to Go » 2. Intermediate » 2.5 Files

Files

In Go, Package ioutil implements some I/O utility functions. But, as of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code.

Reading Files

package main

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

func main() {
	// Open the file
	file, err := os.Open("example.txt")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	defer file.Close()

	// Read the entire content of the file
	content, err := io.ReadAll(file)
	if err != nil {
		fmt.Println("Error reading file:", err)
		return
	}

	fmt.Println("File Content:")
	fmt.Println(string(content))
}

Reading a File Line by Line

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	// Open a file
	file, err := os.Open("example.txt")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	defer file.Close()

	// Create a scanner to read the file line by line
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Println("Line:", line)
	}

	if err := scanner.Err(); err != nil {
		fmt.Println("Error reading file:", err)
	}
}

Writing Files

package main

import (
	"fmt"
	"os"
)

func main() {
	content := []byte("Hello, Golang!")

	// Create or open the file for writing
	file, err := os.Create("example.txt")
	if err != nil {
		fmt.Println("Error creating file:", err)
		return
	}
	defer file.Close()

	// Write content to the file
	_, err = file.Write(content)
	if err != nil {
		fmt.Println("Error writing to file:", err)
		return
	}

	fmt.Println("File written successfully!")
}

File Paths

The path/filepath package provides functions for working with file paths in a platform-independent way.

Joining Path Elements

The filepath.Join function is used to join individual elements of a file path into a single path.

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// Join path elements
	path := filepath.Join("dir", "subdir", "file.txt")
	fmt.Println("Joined path:", path)
}

Getting the Base Name and Directory of a Path

The filepath.Base function returns the last element of a path, and filepath.Dir returns the directory of a path.

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// Get base name and directory
	path := "/path/to/file.txt"
	base := filepath.Base(path)
	dir := filepath.Dir(path)

	fmt.Println("Base:", base)
	fmt.Println("Directory:", dir)
}

Cleaning and Resolving Paths

The filepath.Clean function returns the shortest path name equivalent to the input path, and filepath.Abs returns an absolute representation of a path.

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// Clean and resolve paths
	uncleanPath := "/path/../file.txt"
	cleanPath := filepath.Clean(uncleanPath)

	absPath, err := filepath.Abs(uncleanPath)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Unclean path:", uncleanPath)
	fmt.Println("Clean path:", cleanPath)
	fmt.Println("Absolute path:", absPath)
}

Directories

package main

import (
	"fmt"
	"os"
)

func main() {
	// Create a directory
	err := os.Mkdir("mydirectory", 0755)
	if err != nil {
		fmt.Println("Error creating directory:", err)
		return
	}

	fmt.Println("Directory created successfully!")

	// Remove a directory
	err = os.Remove("mydirectory")
	if err != nil {
		fmt.Println("Error removing directory:", err)
		return
	}

	fmt.Println("Directory removed successfully!")
}

Temporary Files and Directories

In Go, you can use the os and io packages to work with temporary files and directories.

Temporary File

package main

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

func main() {
	// Create a temporary file
	tempFile, err := os.CreateTemp("", "example")
	if err != nil {
		fmt.Println("Error creating temporary file:", err)
		return
	}
	defer os.Remove(tempFile.Name()) // Clean up: remove the temporary file when done

	// Write some data to the temporary file
	data := []byte("Hello, temporary file!\n")
	_, err = tempFile.Write(data)
	if err != nil {
		fmt.Println("Error writing to temporary file:", err)
		return
	}

	// Read from the temporary file
	tempFile.Seek(0, io.SeekStart)
	buffer := make([]byte, len(data))
	_, err = tempFile.Read(buffer)
	if err != nil {
		fmt.Println("Error reading from temporary file:", err)
		return
	}

	// Print the contents of the temporary file
	fmt.Println("Contents of the temporary file:")
	fmt.Println(string(buffer))
}

Temporary Directory

package main

import (
	"fmt"
	"os"
)

func main() {
	// Create a temporary directory
	tempDir, err := os.MkdirTemp("", "exampleDir")
	if err != nil {
		fmt.Println("Error creating temporary directory:", err)
		return
	}
	defer os.RemoveAll(tempDir) // Clean up: remove the temporary directory when done

	// Print the path of the temporary directory
	fmt.Println("Temporary directory:", tempDir)

	// You can now use the tempDir for your operations.
	// For example, create a file in the temporary directory:
	tempFile, err := os.CreateTemp(tempDir, "exampleFile.txt")
	if err != nil {
		fmt.Println("Error creating temporary file:", err)
		return
	}
	os.Remove(tempFile.Name()) // Clean up: remove the temporary file when done
}

Code Challenge

Write a Go function that takes two file paths as input and determines if one path is a subpath of the other.

Loading...
> code result goes here
Prev
Next