Home > Backend Development > Golang > How to List a Directory's Contents in Go Without Recursion?

How to List a Directory's Contents in Go Without Recursion?

DDD
Release: 2024-12-31 11:54:11
Original
323 people have browsed it

How to List a Directory's Contents in Go Without Recursion?

Listing Directory Contents in Go Without Recursion

In Go, listing files and folders within a specified directory can be accomplished by leveraging the ReadDir function from the os package. Unlike filepath.Walk, which traverses directories recursively, ReadDir limits its scope to the designated directory.

The ReadDir function returns a slice of os.DirEntry objects, which provide information about each directory entry, including filename and file type. To list the contents of a directory without delving into subdirectories, follow these steps:

package main

import (
    "fmt"
    "os"
    "log"
)

func main() {
    entries, err := os.ReadDir("./")
    if err != nil {
        log.Fatal(err)
    }

    for _, e := range entries {
        fmt.Println(e.Name())
    }
}
Copy after login

In this example, the ReadDir function reads the current directory's contents and stores them in the entries slice. Each os.DirEntry in the slice contains the entry's name, which is then printed to the console.

This approach provides a straightforward method to list the files and folders within a specific directory without exploring subdirectories.

The above is the detailed content of How to List a Directory's Contents in Go Without Recursion?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template