Directories
This Go program demonstrates directory and file manipulation operations using the os
and filepath
packages. Let's go through the code with inline comments and explanations:
Output
Explanation:
Creating and Removing Directories:
os.Mkdir("subdir", 0755)
creates a directory named "subdir" with permissions 0755.defer os.RemoveAll("subdir")
defers the removal of the "subdir" directory until the end of the program.
Creating Empty Files:
createEmptyFile
function creates empty files usingos.WriteFile
.
Nested Directories and Files:
os.MkdirAll("subdir/parent/child", 0755)
creates nested directories.createEmptyFile
is used to create files within the nested directories.
Reading Directory Contents:
os.ReadDir("subdir/parent")
reads the contents of a directory.entry.Name()
andentry.IsDir()
are used to print the name and whether it's a directory or not.
Changing Working Directory:
os.Chdir("subdir/parent/child")
changes the current working directory.os.Chdir("../../..")
changes it back to the root.
Using
filepath.WalkDir
:filepath.WalkDir("subdir", visit)
recursively walks the directory tree and calls thevisit
function for each file or directory.
visit
Function:visit
function is called during thefilepath.WalkDir
traversal.It prints the path and whether it's a directory or not.
This program showcases common file and directory manipulation operations in Go.
Last updated
Was this helpful?