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...

How to remove the first character of a string in Golang

How to remove the first character of a string in Golang

Learn how to remove first the character of a string in GoLang

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.

How to Convert GoLang Integer to String Conversion

How to Convert GoLang Integer to String Conversion

Learn how to convert integers to strings and how to convert strings to integers in GoLang