🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
- Introduction
FprintlnFunction Syntax- Examples
- Basic Usage
- Writing to a File
- Real-World Use Case
- 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: Anio.Writerwhere 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment