GoLang OS Package
Overview
Working with the operating system is a very basic requirement of any programmer. The Golang OS package gives us the ability to work with all things related to OS. In this article, we will learn more about Golang OS.
Introduction
Package OS provides a platform-independent interface to operating system functionality. It is used to deal with programming related to reading and writing files. In this article, we will see a few of them in detail and implement examples using the Golang OS package.
GoLang OS Package – Open and Read a File
The below example shows us how we can open and read a file from the directory structure.
Make and Change Directories Using Go OS Package
The Mkdir () function is used to create a new directory structure and Chdir() is used to change the directory in the Golang application. In the below example, we will create a program where we create a file by using the Mkdir() and Chdir() functions from the Golang OS package.
Other Important OS Package Functions
- func Clearenv() Clearance deletes all environment variables.
- func Environ() []string Environ returns a copy of strings representing the environment, in the form key=value.
- func Getwd() Get returns a rooted path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.
- func Hostname() Hostname returns the hostname reported by the kernel.
- func Remove(name) Remove removes the named file or (empty) directory.
- func RemoveAll(name) RemoveAll removes the path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil.
- func Rename(old_path, new_path) Rename renames (moves) the old path to a new path. If newpath already exists and is not a directory, Rename replaces it.
- func SameFile(file1, file2) The same file reports whether file1 and file2 describe the same file.
Conclusion
- Learned in-depth about Golang OS.
- Implemented Examples using the Golang OS package.