×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

How to read the contents of a file using syscall in Golang?

Here, we will learn to read the contents of a file using syscall in Golang.
Submitted by IncludeHelp, on November 13, 2021 [Last updated : March 05, 2023]

Reading the contents of a file using syscall in Golang

In the Go programming language, to read the contents of a file using syscall – we use the Read() function of the syscall package. The Read() function is used to read the content of the file and returns the length of the file and error if any.

Syntax

func Read(fd int, p []byte) (n int, err error)

Consider the below example demonstrating how to read the contents of a file using syscall in Golang?

The file is:

File name: test.txt
File content:
Hello, world! How are you?

Golang code to read the contents of a file using syscall

package main

import (
	"fmt"
	"syscall"
)

func main() {
	// Creating a byte buffer to
	// store the file's content
	var filedata = make([]byte, 64)
	// Opening the file in Read-only mode
	fd, err := syscall.Open("test.txt", syscall.O_RDONLY, 0777)
	if err != nil {
		fmt.Println("Err:", err)
	}
	for {
		// Reading the content
		len, _ := syscall.Read(fd, filedata)
		if len <= 0 {
			break
		}
		
		fmt.Println("The file's content is...")
		fmt.Print(string(filedata[:len]))
	}
}

Output

The file's content is...
Hello, world! How are you?

Golang syscall Package Programs »





Comments and Discussions!

Load comments ↻





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