Golang

extra-content in golang

File management in golang

package main

import (
	"fmt"
	"os"
)

func main() {
	file, _ := os.Create("output.txt")
	defer file.Close()

	fmt.Fprintln(file, "Hello file!")   // Writes to the file
	fmt.Fprintf(file, "Number: %d", 42) // Writes formatted output
}

 

Logging in golang

package main

import (
	"log"
	"os"
)

func main() {
	// Set log flags for date, time, and file line number
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	// Open the file in append mode, create it if it doesn't exist, and write-only
	file, err := os.OpenFile("log.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatal("Failed to open file:", err)
	}
	defer file.Close()

	// Set log output to the file
	log.SetOutput(file)

	// Log a message
	log.Println("File opened successfully and logging started.")
}

 

Example:

var name string
fmt.Scanln(&name)       // User input: Amrit
fmt.Println("Hello", name) // Output: Hello Amrit

data := "42 apples"
var n int
var fruit string
fmt.Sscanf(data, "%d %s", &n, &fruit)
fmt.Println(n, fruit) // Output: 42 apples

 

 

 

 


About author

author image

Amrit panta

Fullstack developer, content creator



Scroll to Top