Q:

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

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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?

Program:

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?

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now