Exporing files and folder from the GoLang OS pacckage

Kassim Damilola
Nov 6 · 2 min read
files and folder

In Go, files are a simple struct type that implements certain methods

https://golang.org/src/os/types.go?s=369:411#L6

This article explores the various methods and operations implemented by the file struct type using the os package. (Note: It is possible to use the io package for other file operation).

Open

The open method returns a pointer to the named file, the returned file can be used for reading; and the associated file descriptor. The retured file can now be used in I/O operations.

file, err := os.Open("test.txt")
...
fmt.Println(file)
> &{0xc00007e780}

The OpenFile method allows for the option of creating a file if it doesnt exist.

f, err := os.OpenFile("test2.txt", os.O_RDWR|os.O_CREATE, 0755)

The Close() closes the File, rendering it unusable for I/O.

File permision with Chmod() andChown()

err := os.Chmod("test.txt", 0444) //Read only
err := os.Chmod("test.txt", 0222) //Make writtable

Reads — Read, Readdir, ReadAt, Readdiranmes

> Read returns a specific byte size of the given file

...
data := make([]byte, 10)
content , err := file.Read(data)

This would return the first 10 nbyte of data in the specied file

> Readdir: returns the list of files in a direct

folder, err := os.Open("testF")
...
files, err := folder.Readdir(0)
...
for _, var := range files {
fmt.Println(var.Name())
}

>ReadAt: Just like read, read at gives takes an offset parameter

...
data := make([]byte, 10)
content , err := file.Read(data , 2)// Skip the first two byte

> Readdirnames: In place of returning file pointers as the Readir(), this would return an array of the file names in a directory

Writes — Write, WritaAt, Writestring

> Writestring

file, err := os.Create("test2.txt")
...
l, err := file.WriteString("File contents")
...

> Write: Write method to write a slice of bytes to a file named

data := []byte{104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100}
n2, err := file.Write(data)
...

Others

> Stat() returnsFileInfo structure > &{test.txt 32 {2456229631 30774379} {854005597 30774426} {1742385088 30774425} 0 29 0 1 {0 0} 1455739725 4980736 228973 false} <nil>
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade