Golang fmt Fprintf Function

The fmt.Fprintln function in Golang is part of the fmt package. It writes formatted data followed by a newline character to any io.Writer, such as a file, buffer, or network connection. This function is useful for generating line-separated output to various destinations.

Table of Contents

  1. Introduction
  2. Fprintln Function Syntax
  3. Examples
    • Basic Usage
    • Writing to a File
  4. Real-World Use Case
  5. Conclusion

Introduction

The fmt.Fprintln function writes arguments to an io.Writer with a newline at the end. It is similar to fmt.Println but directs the output to a specified writer. This function is handy for writing logs, generating text files, or creating network messages where line separation is needed.

Fprintln Function Syntax

The syntax for the fmt.Fprintln function is as follows:

func Fprintln(w io.Writer, a ...interface{}) (n int, err error)

Parameters:

  • w: An io.Writer where the output is written.
  • a: The arguments to be written. Each argument is separated by a space, and a newline is appended at the end.

Returns:

  • n: The number of bytes written.
  • err: An error if one occurred during writing.

Examples

Basic Usage

This example demonstrates how to use the fmt.Fprintln function to write text to a string buffer.

Example

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var buffer bytes.Buffer

	// Use fmt.Fprintln to write text to the buffer
	fmt.Fprintln(&buffer, "Hello,", "world!")

	// Print the contents of the buffer
	fmt.Println(buffer.String())
}

Output:

Hello, world!

Writing to a File

You can use fmt.Fprintln to write line-separated text to a file.

Example

package main

import (
	"fmt"
	"os"
)

func main() {
	// Open a file for writing
	file, err := os.Create("output.txt")
	if err != nil {
		fmt.Println("Error creating file:", err)
		return
	}
	defer file.Close()

	// Use fmt.Fprintln to write text to the file
	fmt.Fprintln(file, "First line of text.")
	fmt.Fprintln(file, "Second line of text.")

	fmt.Println("Data written to file successfully.")
}

Output in output.txt:

First line of text.
Second line of text.

Real-World Use Case

Logging to a File

In real-world applications, fmt.Fprintln can be used to log messages to a file with each log entry on a new line.

Example

package main

import (
	"fmt"
	"os"
)

func logToFile(message string) error {
	// Open a log file in append mode
	file, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	// Write the log message to the file
	_, err = fmt.Fprintln(file, message)
	return err
}

func main() {
	err := logToFile("Application started.")
	if err != nil {
		fmt.Println("Error logging to file:", err)
		return
	}

	fmt.Println("Log entry created.")
}

Output in app.log:

Application started.

Conclusion

The fmt.Fprintln function is useful for writing formatted output with line separation to any writer implementing the io.Writer interface. It is ideal for applications that require line-based output to files, buffers, or network connections, making it a practical choice for logging and data generation in Go programs.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare