Code with Go
About
  • Code With Go! 🚀
  • Hello World
  • Values
  • Variables
  • Constants
  • For Loop
  • If Else
  • Switch
  • Array
  • Slice
  • Map
  • Range
  • Functions
  • Multiple Return Values
  • Variadic Functions
  • Closure
  • Recursion
  • Pointers
  • Strings and Runes
  • Structs
  • Methods
  • Interfaces
  • Struct Embedding
  • Generics
  • Error
  • Goroutines
  • Channels
  • Channel Buffering
  • Channel Synchronization
  • Channel Directions
  • Select
  • Timeouts
  • Non-Blocking Channel Operations
  • Closing Channels
  • Range over Channels
  • Timers
  • Tickers
  • Worker Pools
  • Wait Groups
  • Rate Limiting
  • Atomic Counters
  • Mutexes
  • Stateful Goroutines
  • Sorting
  • Sorting by Functions
  • Panic
  • Defer
  • Recover
  • String Functions
  • String Formatting
  • Text Templates
  • Regular Expressions
  • JSON
  • XML
  • Time
  • Epoch
  • Time Formatting / Parsing
  • Random Numbers
  • Number Parsing
  • SHA256 Hashes
  • Base64 Encoding
  • Reading Files
  • Writing Files
  • Line Filters
  • File Paths
  • Directories
  • Temporary Files and Directories
  • Embed Directive
  • Testing and Benchmarking
  • Command-Line Arguments
  • Command-Line Flags
  • Command-Line Subcommands
  • Environment Variables
  • Logging
  • HTTP Client
  • HTTP Server
  • Context
  • Spawning Processes
  • Exec'ing Processes
  • Signals
  • Exit
  • Resize Image
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub

Temporary Files and Directories

This Go program demonstrates the usage of temporary files and directories using the os and filepath packages. Let's go through the code with inline comments and explanations:

// Importing necessary packages.
import (
	"fmt"
	"os"
	"path/filepath"
)

// Function to check and panic if an error occurs.
func check(e error) {
	if e != nil {
		panic(e)
	}
}

// Main function where the execution of the program begins.
func main() {
	// Creating a temporary file with the prefix "sample" in the default temporary directory.
	f, err := os.CreateTemp("", "sample")
	check(err)

	fmt.Println("Temp file name:", f.Name())

	// Defer removing the temporary file at the end of the program.
	defer os.Remove(f.Name())

	// Writing data to the temporary file.
	_, err = f.Write([]byte{1, 2, 3, 4})
	check(err)

	// Creating a temporary directory with the prefix "sampledir" in the default temporary directory.
	dname, err := os.MkdirTemp("", "sampledir")
	check(err)

	fmt.Println("Temp dir name:", dname)

	// Defer removing the temporary directory and its contents at the end of the program.
	defer os.RemoveAll(dname)

	// Creating a file inside the temporary directory and writing data to it.
	fname := filepath.Join(dname, "file1")
	err = os.WriteFile(fname, []byte{1, 2}, 0666)
	check(err)
}

output

Temp file name: ..\..\....\.......\Temp\sample4108738795
Temp dir name: ..\..\....\.......\Temp\sampledir1931724887

Explanation:

  1. Creating a Temporary File:

    • os.CreateTemp("", "sample") creates a temporary file in the default temporary directory with the prefix "sample."

    • defer os.Remove(f.Name()) defers the removal of the temporary file until the end of the program.

  2. Writing Data to the Temporary File:

    • f.Write([]byte{1, 2, 3, 4}) writes data to the temporary file.

  3. Creating a Temporary Directory:

    • os.MkdirTemp("", "sampledir") creates a temporary directory in the default temporary directory with the prefix "sampledir."

    • defer os.RemoveAll(dname) defers the removal of the temporary directory and its contents until the end of the program.

  4. Creating a File Inside the Temporary Directory:

    • filepath.Join(dname, "file1") constructs the path for a file inside the temporary directory.

    • os.WriteFile(fname, []byte{1, 2}, 0666) creates the file and writes data to it.

This program showcases how to create and work with temporary files and directories in Go.

PreviousDirectoriesNextEmbed Directive

Last updated 1 year ago

Was this helpful?