Get The Names Of All The Files Inside A Directory Using GoLang

Get The Names Of All The Files Inside A Directory Using GoLang

Learn how to get list all the file names inside of a directory using golang

In this short tutorial, we will learn how to get all the file names from a directory.

List File Names

To get all the files inside a directory we will use the ReadDir function from the ioutil package.

func GetFileNames(path string) ([]string, error) {

	// Get files in a directory.
	files, err := ioutil.ReadDir(path)
   
	// Check for error.
	if err != nil {
		return nil, err
	}

	// Create slice of strings to hold file names.
	names := make([]string, len(files))

	// Iterate over the files and append the file name to the names slice.
	for _, file := range files {
		names = append(names, file.Name())
	}
	
	sort.Strings(names)

	return names, nil
}

Did you like it? Why don't you try also...

Is String a Palindrome?

Is String a Palindrome?

Learn How to Test if a String is a Palindrome in Go.

How to Find the Maximum Integer Value In a GoLang Slice

How to Find the Maximum Integer Value In a GoLang Slice

Learn to Find the Maximum Integer Value In a GoLang Slice

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.