Golang os.O_APPEND Constant with Examples

Golang | os.O_APPEND Constant: Here, we are going to learn about the O_APPEND constant of the os package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 23, 2021

os.O_APPEND

In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The O_APPEND constant is used to append data to the file when writing i.e., enables to append data to the file.

The value of the O_APPEND constant is 1024.

Syntax:

O_APPEND int

Implementation in the package source code:

const O_APPEND int = syscall.O_APPEND

Parameter(s):

  • None

Return Value:

The return type of the os.O_APPEND constant is an int, it returns 1024 i.e., the value of the O_APPEND constant is 1024.

Example 1:

// Golang program to demonstrate the
// example of O_APPEND constant

package main

import (
	"fmt"
	"os"
)

func main() {
	// Printing the type and value
	fmt.Printf("Type of os.O_APPEND: %T\n",
		os.O_APPEND)
	fmt.Printf("Value of os.O_APPEND: %d\n",
		os.O_APPEND)
}

Output:

Type of os.O_APPEND: int
Value of os.O_APPEND: 1024

Example 2:

The below code appends a line of text to the file file.log. It creates the file if it doesn’t already exist.

// Golang program to demonstrate the
// example of O_APPEND constant

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	f, err := os.OpenFile("file.log",
		os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Println(err)
	}
	fmt.Println("File created....")

	defer f.Close()
	if _, err := f.WriteString("Hello, world!\n"); err != nil {
		log.Println(err)
	}

	fmt.Println("Data appended....")
}

Output:

File created....
Data appended....

Content of the file ("file.log")

Hello, world!

Golang os Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.