
- Go - Home
- Go - Overview
- Go - Environment Setup
- Go - Program Structure
- Go - Basic Syntax
- Go - Data Types
- Go - Variables
- Go - Constants
- Go - Identifiers
- Go - Keywords
- Go - Operators
- Go - Arithmetic Operators
- Go - Assignment Operators
- Go - Relational Operators
- Go - Logical Operators
- Go - Bitwise Operators
- Go - Miscellaneous Operators
- Go - Operators Precedence
- Go Decision Making
- Go - Decision Making
- Go - If Statement
- Go - If Else Statement
- Go - Nested If Statements
- Go - Switch Statement
- Go - Select Statement
- Go Control Flow Statements
- Go - For Loop
- Go - Nested for Loops
- Go - Break Statement
- Go - Continue Statement
- Go - Goto Statement
- Go Functions
- Go - Functions
- Go - Call by Value
- Go - Call by Reference
- Go - Functions as Values
- Go - Function Closure
- Go - Function Method
- Go - Anonymous function
- Go Strings
- Go - Strings
- Go - String Length
- Go - String Concatenation
- Go - Compare Strings
- Go - Split String
- Go - Substring Extraction
- Go - String Replacement
- Go - String Interpolation
- Go - Parse Date Strings
- Go Arrays
- Go - Arrays
- Go - Multidimensional Arrays
- Go - Multidimensional Arrays
- Go - Passing Arrays to Functions
- Go - Pointers
- Go - Pointers
- Go - Array of pointers
- Go - Pointer to pointer
- Go - Passing pointers to functions
- Go Advanced Control Structures
- Go - Scope Rules
- Go - Dereferencing Pointer
- Go - Structures
- Go - Slice
- Go - Slice of Slices
- Go - Range
- Go - Maps
- Go - Recursion
- Go - Type Casting
- Go - Interfaces
- Go - Type Assertion
- Go - Error Handling
- Go - Concurrency
- Go - Regular Expression
- Go - Inheritance
- Go - Packages
- Go - Templates
- Go - Reflection
- Go - Generics
- Go File Handling
- Go - Read File By Word
- Go - Read File By Line
- Go - Read CSV Files
- Go - Delete File
- Go - Rename & Move File
- Go - Truncate a File
- Go - File Read-Write Mode W/O Truncation
- Go Miscellaneous
- Go - defer Keyword
- Go - Fmt Package
- Go - Zero Value
- Go - Import
Go - File Read-Write Mode Without Truncation
In this golang chapter, we are going to use os.OpenFile() and ioutil.Readfile() to append the given file without truncating it. In the first Example, we are going to Os.Openfile to access the file and then by using file.WriteString function we will append it. In the second Example, we will use ioutil,ReadFile(), ioutil.WriteFile() and Append() functions to perform the same operation on the file without truncating it respectively.
Syntax
file.read()
The Read() function is used to read the contents of a file. The function accepts the file whose contents are to be read as an argument and returns the contents of the file along with an error variable.
os.Openfile()
This function is a part of os package. It is used to open a file to read. It takes one input i.e. the filename which will be opened.
file.WriteString()
In Go programming language, WriteString method is used to write a string to a file. The string is passed as an argument in the function as str.
ioutil.ReadFile()
This function is available in the ioutil package and is used to read the contents of a file with filename as an input in the function.
ioutil.WriteFile()
In Go, WriteFile belongs to ioutil package and contains three parameters, the first is the filename where data is to be written, second is the data which is to be written and third is the file permission. The data is written to the file if function is executed successfully.
Non-Truncating Read-Write File Handling
In this method we will write a go language program to open a file in the read write mode without truncating the file by using various functions present in os package.
Algorithm
First, we need to import the "fmt" and "os" packages.
Then start the main() function. Inside the main() function call the OpenFile() function to open the provided file and pass the required arguments as the name of file along with flags to be used when opening the file (os.O_RDWR), and Unix-style permissions for the file as arguments to the function.
Check if there was an error opening the file. If so, print an error message on the screen. Use the file.Close() function in order to close the file.
Use the "file.WriteString" method to write a string of data to the end of the file. Check if there was an error writing to the file. If so, print an error message.
Use the "file.Seek" method to move the position in the file to the beginning. Use the "io.ReadAtLeast" method to read a specified number of bytes from the file.
Check if there was an error reading from the file. If so, print an error message. Otherwise print the data of the file.
Example
In the following Example, we will learn how to use OS package of Golang to open a file in read-write mode without truncating it.
package main import ( "fmt" "os" ) func main() { // Open file in read-write mode without truncating it file, err := os.OpenFile("newfile.txt", os.O_RDWR, 0644) if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() // Write data to the file _, err = file.WriteString("Hello World!\n") if err != nil { fmt.Println("Error writing to file:", err) return } // Move the position in the file to the beginning _, err = file.Seek(0, 0) if err != nil { fmt.Println("Error seeking in file:", err) return } // Read data from the file data := make([]byte, 14) _, err = file.Read(data) if err != nil { fmt.Println("Error reading from file:", err) return } fmt.Println("Data read from file:", string(data)) }
Output
Data read from file: Hello World!
Read-Modify-Write File Handling using ioutil
In this method, we will write the go language program to open a file in the read write mode without truncating the file by using various functions present in ioutil package.
Algorithm
First, we need to import the "fmt" and "io/ioutil" packages.
Then start the main() function. Inside the main() call the ReadFile() function present in the ioutil package to read the entire contents of the file into a byte slice.
Check if there was an error reading the file. If the error is received then we need toprint the error message on the screen.
Use the append() function to add data to the file specified.
Call the WriteFile() function and pass in the name of the file to be opened, the modified byte slice, and the Unix-style permissions for the file.
Check if there was an error writing to the file. If so, print an error message on the screen. Otherwise print that the data is read from the file.
Example
In the following Example,we are going to open a file in read-write mode, using ioutil package of golang.
package main import ( "fmt" "io/ioutil" ) func main() { // Read data from the file data, err := ioutil.ReadFile("notepad.txt") if err != nil { fmt.Println("Error reading from file:", err) return } // Modify the data data = append(data, []byte("\nHello, World")...) // Write the modified data back to the file err = ioutil.WriteFile("notepad1.txt", data, 0644) if err != nil { fmt.Println("Error writing to file:", err) return } fmt.Println("Data read from the file.", string(data)) }
Output
Data read from the file. Hello, World
We have successfully compiled and executed a go language program to open a file in read-write mode without truncating the file along with Examples.Here we have used two Examples to implement the result. In the first Example we are using the functions present in the os package while in the second Example we are using the ioutil package to implement the result. The "os" package provides more control over the file operations, while the "ioutil" package provides easier file operations with lesser code. Both Examples have their own advantages and can be used depending on the requirement of the application.