ADVERTISEMENT
ADVERTISEMENT

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

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?

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?

Golang syscall Package Programs »



ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.