TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Fprint, Fprintf and Fprintln Examples (fmt)

Use the Fprint, Fprintf and Fprintln methods from fmt to write data to a file.
Fprint. The entire point of a file is to write things to it—to store data in it, in a persistent way. With Fprint and its family members, we can use fmt.Print() but target a file.fmt
The names of these methods is confusing. F stands for file. And we use a method like Fprintf just like fmt.Printf—we provide a format string. A first argument (the file) must be provided.File
A complete example. This program uses Fprint, Fprintf and Fprintln together. With Fprint, no newline is added at the end—this helps when not writing a file of lines.

Result: The program, once executed, will write several times to a file (you can change the path in the program).

Golang program that uses Fprint, Fprintf, Fprintln package main import ( "bufio" "fmt" "os" ) func main() { // Create a file and use bufio.NewWriter. f, _ := os.Create("C:\\programs\\file.txt") w := bufio.NewWriter(f) // Use Fprint to write things to the file. // ... No trailing newline is inserted. fmt.Fprint(w, "Hello") fmt.Fprint(w, 123) fmt.Fprint(w, "...") // Use Fprintf to write formatted data to the file. value1 := "cat" value2 := 900 fmt.Fprintf(w, "%v %d...", value1, value2) fmt.Fprintln(w, "DONE...") // Done. w.Flush() } Output Hello123...cat 900...DONE...
Notes, file print methods. Other methods, like WriteString() on bufio can also be used to write to a file. And these may be simpler in many programs.

However: For more advanced things, like using format strings, a func like Fprintf can lead to clearer code.

A summary. Writing to files is a core reason for Go's existence. Go is meant to be useful in real-world tasks. Fprint and similar methods offer a powerful tool for file writing.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf