Golang offers a vast inbuilt library that can be used to perform read and write operations on files. In order to read from files on the local system, the io/ioutil module is put to use. The io/ioutil module is also used to write content to the file.
The fmt module implements formatted I/O with functions to read input from the stdin and print output to the stdout. The log module implements simple logging package. It defines a type, Logger, with methods for formatting the output. The os module provides the ability to access native operating-system features. The bufio module implements buffered I/O which helps to improve the CPU performance.
- os.Create() : The os.Create() method is used to creates a file with the desired name. If a file with the same name already exists, then the create function truncates the file.
- ioutil.ReadFile() : The ioutil.ReadFile() method takes the path to the file to be read as it’s the only parameter. This method returns either the data of the file or an error.
- ioutil.WriteFile() : The ioutil.WriteFile() is used to write data to a file. The WriteFile() method takes in 3 different parameters, the first is the location of the file we wish to write to, the second is the data object, and the third is the FileMode, which represents the file’s mode and permission bits.
- log.Fatalf : Fatalf will cause the program to terminate after printing the log message. It is equivalent to Printf() followed by a call to os.Exit(1).
- log.Panicf : Panic is just like an exception that may arise at runtime. Panicln is equivalent to Println() followed by a call to panic(). The argument passed to panic() will be printed when the program terminates.
- bufio.NewReader(os.Stdin) : This method returns a new Reader whose buffer has the default size(4096 bytes).
- inputReader.ReadString(‘\n’) : This method is used to read user input from stdin and reads until the first occurrence of delimiter in the input, returning a string containing the data up to and including the delimiter. If an error is encountered before finding a delimiter, it returns the data read before the error and the error itself.
Example 1: Use the offline compiler for better results. Save the file with .go extension. Use the command below command to execute the program.
go run filename.go
// Golang program to read and write the files package main // importing the packages import ( "fmt" "io/ioutil" "log" "os") func CreateFile() { // fmt package implements formatted // I/O and has functions like Printf // and Scanf fmt.Printf("Writing to a file in Go lang\n") // in case an error is thrown it is received // by the err variable and Fatalf method of // log prints the error message and stops // program execution file, err := os.Create("test.txt") if err != nil { log.Fatalf("failed creating file: %s", err) } // Defer is used for purposes of cleanup like // closing a running file after the file has // been written and main //function has // completed execution defer file.Close() // len variable captures the length // of the string written to the file. len, err := file.WriteString("Welcome to GeeksforGeeks."+ " This program demonstrates reading and writing"+ " operations to a file in Go lang.") if err != nil { log.Fatalf("failed writing to file: %s", err) } // Name() method returns the name of the // file as presented to Create() method. fmt.Printf("\nFile Name: %s", file.Name()) fmt.Printf("\nLength: %d bytes", len) } func ReadFile() { fmt.Printf("\n\nReading a file in Go lang\n") fileName := "test.txt" // The ioutil package contains inbuilt // methods like ReadFile that reads the // filename and returns the contents. data, err := ioutil.ReadFile("test.txt") if err != nil { log.Panicf("failed reading data from file: %s", err) } fmt.Printf("\nFile Name: %s", fileName) fmt.Printf("\nSize: %d bytes", len(data)) fmt.Printf("\nData: %s", data) } // main function func main() { CreateFile() ReadFile() } |
Output:

Example 2: Golang Program code that accepts user input to read and write the files.
// Golang program to read and write the files package main // importing the requires packages import ( "bufio" "fmt" "io/ioutil" "log" "os") func CreateFile(filename, text string) { // fmt pacakge implements formatted I/O and // contains inbuilt methods like Printf // and Scanf fmt.Printf("Writing to a file in Go lang\n") // Creating the file using Create() method // with user inputted filename and err // variable catches any error thrown file, err := os.Create(filename) if err != nil { log.Fatalf("failed creating file: %s", err) } // closing the running file after the main // method has completed execution and // the writing to the file is complete defer file.Close() // writing data to the file using // WriteString() method and the // length of the string is stored // in len variable len, err := file.WriteString(text) if err != nil { log.Fatalf("failed writing to file: %s", err) } fmt.Printf("\nFile Name: %s", file.Name()) fmt.Printf("\nLength: %d bytes", len) } func ReadFile(filename string) { fmt.Printf("\n\nReading a file in Go lang\n") // file is read using ReadFile() // method of ioutil package data, err := ioutil.ReadFile(filename) // in case of an error the error // statement is printed and // program is stopped if err != nil { log.Panicf("failed reading data from file: %s", err) } fmt.Printf("\nFile Name: %s", filename) fmt.Printf("\nSize: %d bytes", len(data)) fmt.Printf("\nData: %s", data) } // main function func main() { // user input for filename fmt.Println("Enter filename: ") var filename string fmt.Scanln(&filename;) // user input for file content fmt.Println("Enter text: ") inputReader := bufio.NewReader(os.Stdin) input, _ := inputReader.ReadString('\n') // file is created and read CreateFile(filename, input) ReadFile(filename) } |
Output:

Recommended Posts:
- How to read and write JSON file using Node.js ?
- CSS | :read-write Selector
- How to Remove All Directories and Files in Golang?
- io.SectionReader.Read() Function in Golang with Examples
- io.PipeReader.Read() Function in Golang with Examples
- How to Read a File Line by Line to String in Golang?
- How to write backslash in Golang string?
- io.PipeWriter.Write() Function in Golang with Examples
- How to select and upload multiple files with HTML and PHP, using HTTP POST?
- How to recursively delete a directory and its entire contents (files + sub dirs) in PHP?
- Why Express ‘app’ and ‘server’ files kept separately ?
- Header files in C/C++ and its uses
- How to create and read value from cookie ?
- How to assign and read values of two different submit buttons using AngularJS ?
- How to open a PDF files in web browser using PHP?
- Creating a dataframe using Excel files
- Deleting all files from a folder using PHP
- How to include() all PHP files from a directory ?
- How to load CSS files using JavaScript?
- Perl | Creating Excel Files
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

