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
+8.7k Golang : Bcrypting password
+28.4k Golang : How to verify uploaded file is image or allowed file types
+13.4k Golang : package is not in GOROOT during compilation
+10k Golang : Concatenate (combine) buffer data example
+20.2k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+13.2k Golang : Overwrite previous output with count down timer
+13.5k Golang : Rename directory
+4.7k Javascript : How to refresh page with JQuery ?
+8.4k Golang : Qt get screen resolution and display on center example
+9.6k Golang : Get local time and equivalent time in different time zone
+29.9k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+4.2k PHP : See installed compiled-in-modules