Wednesday, 18 November 2020

golang20 list the files in a folder

 C:\Users\bob\golang11>go run main.go
a.txt
SSMS-Setup-ENU.exe
w3school.jpg

------------------------
package main

import (
"fmt"
"log"
"os"
"path"
"path/filepath"
"runtime"
)

func rootDir() string {
_, b, _, _ := runtime.Caller(0)
d := path.Join(path.Dir(b))
return filepath.Dir(d)
}

func main() {
dirname := rootDir() + "\\golang9\\download"

f, err := os.Open(dirname)
if err != nil {
log.Fatal(err)
}
files, err := f.Readdir(-1)
f.Close()
if err != nil {
log.Fatal(err)
}

for _, file := range files {
fmt.Println(file.Name())
}
}

No comments:

Post a Comment