Golang : File system scanning
Problem :
How to scan all the files located inside a root directory in Golang?
Solution :
Use the filepath.Walk
function. See codes below :
package main
import (
"fmt"
"os"
"path/filepath"
)
func scan(path string, f os.FileInfo, err error) error {
fmt.Printf("Scanned %s with size %d bytes\n", path, f.Size())
return nil
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("USAGE : %s <target_directory> \n", os.Args[0])
os.Exit(0)
}
dir := os.Args[1] // 1st argument is the directory location
err := filepath.Walk(dir, scan)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Sample output :
./scanfilesystem /Users/
Scanned /Users/ with size 170 bytes
Scanned /Users/.localized with size 0 bytes
Scanned /Users/Shared with size 136 bytes
Scanned /Users/Shared/.localized with size 0 bytes
Scanned /Users/Shared/SC Info with size 68 bytes
Scanned /Users/sweetlogic with size 8194 bytes
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+27.5k PHP : Convert(cast) string to bigInt
+21.5k Golang : Encrypt and decrypt data with TripleDES
+17k Golang : Covert map/slice/array to JSON or XML format
+11.6k Golang : Find age or leap age from date of birth example
+6k Java : Human readable password generator
+11.4k Golang : Change date format to yyyy-mm-dd
+10k Golang : Test a slice of integers for odd and even numbers
+18k Golang : Check if a directory exist or not
+21.2k Golang : Create and resolve(read) symbolic links
+10k Golang : Setting variable value with ldflags
+8.9k Golang : Populate or initialize struct with values example
+5.2k Golang : Get FX sentiment from website example