Introduction

The gfile file management component provides more comprehensive file/directory operation capabilities.

Usage:

  1. import "github.com/gogf/gf/v2/os/gfile"

Interface Documentation:

https://pkg.go.dev/github.com/gogf/gf/v2/os/gfile

File - 图1tip

The following list includes commonly used methods, and the documentation may lag behind new features in the code. For more methods and examples, please refer to the code documentation: https://pkg.go.dev/github.com/gogf/gf/v2/os/gfile

Content Management

GetContents

  • Description: Reads the content of the specified file path and returns it as a string.
  • Format:
  1. func GetContents(path string) string
  • Example:
  1. func ExampleGetContents() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // It reads and returns the file content as string.
  11. // It returns empty string if it fails reading, for example, with permission or IO error.
  12. fmt.Println(gfile.GetContents(tempFile))
  13. // Output:
  14. // goframe example content
  15. }

GetContentsWithCache

  • Description: Reads the file content with caching, allowing for cache timeout settings. The cache is automatically cleared when the file changes.
  • Format:
  1. func GetContentsWithCache(path string, duration ...time.Duration) string
  • Example:
  1. func ExampleGetContentsWithCache() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_cache")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // It reads the file content with cache duration of one minute,
  11. // which means it reads from cache after then without any IO operations within on minute.
  12. fmt.Println(gfile.GetContentsWithCache(tempFile, time.Minute))
  13. // write new contents will clear its cache
  14. gfile.PutContents(tempFile, "new goframe example content")
  15. // There's some delay for cache clearing after file content change.
  16. time.Sleep(time.Second * 1)
  17. // read contents
  18. fmt.Println(gfile.GetContentsWithCache(tempFile))
  19. // May Output:
  20. // goframe example content
  21. // new goframe example content
  22. }

GetBytesWithCache

  • Description: Reads the file content with caching, allowing for cache timeout settings. The cache is automatically cleared when the file changes, and the content is returned as a byte slice.
  • Format:
  1. func GetBytesWithCache(path string, duration ...time.Duration) []byte
  • Example:
  1. func ExampleGetBytesWithCache() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_cache")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // It reads the file content with cache duration of one minute,
  11. // which means it reads from cache after then without any IO operations within on minute.
  12. fmt.Println(gfile.GetBytesWithCache(tempFile, time.Minute))
  13. // write new contents will clear its cache
  14. gfile.PutContents(tempFile, "new goframe example content")
  15. // There's some delay for cache clearing after file content change.
  16. time.Sleep(time.Second * 1)
  17. // read contents
  18. fmt.Println(gfile.GetBytesWithCache(tempFile))
  19. // Output:
  20. // [103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
  21. // [110 101 119 32 103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
  22. }

GetBytes

  • Description: Reads the content of the specified file path and returns it as a byte slice.
  • Format:
  1. func GetBytes(path string) []byte
  • Example:
  1. func ExampleGetBytes() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // It reads and returns the file content as []byte.
  11. // It returns nil if it fails reading, for example, with permission or IO error.
  12. fmt.Println(gfile.GetBytes(tempFile))
  13. // Output:
  14. // [103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
  15. }

GetBytesTilChar

  • Description: Reads the file content up to a specified character and returns the content as a byte slice.
  • Format:
  1. func GetBytesTilChar(reader io.ReaderAt, char byte, start int64) ([]byte, int64)
  • Example:
  1. func ExampleGetBytesTilChar() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. f, _ := gfile.OpenWithFlagPerm(tempFile, os.O_RDONLY, gfile.DefaultPermOpen)
  11. // GetBytesTilChar returns the contents of the file as []byte
  12. // until the next specified byte `char` position.
  13. char, i := gfile.GetBytesTilChar(f, 'f', 0)
  14. fmt.Println(char)
  15. fmt.Println(i)
  16. // Output:
  17. // [103 111 102]
  18. // 2
  19. }

GetBytesByTwoOffsets

  • Description: Reads the file content from the specified range and returns it as a byte slice.
  • Format:
  1. func GetBytesByTwoOffsets(reader io.ReaderAt, start int64, end int64) []byte
  • Example:
  1. func ExampleGetBytesByTwoOffsets() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. f, _ := gfile.OpenWithFlagPerm(tempFile, os.O_RDONLY, gfile.DefaultPermOpen)
  11. // GetBytesTilChar returns the contents of the file as []byte
  12. // until the next specified byte `char` position.
  13. char := gfile.GetBytesByTwoOffsets(f, 0, 3)
  14. fmt.Println(char)
  15. // Output:
  16. // [103 111 102]
  17. }

PutContents

  • Description: Writes string content to the specified file path. If the file does not exist, it will be created recursively.
  • Format:
  1. func putContents(path string, data []byte, flag int, perm os.FileMode) error
  • Example:
  1. func ExamplePutContents() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // It creates and puts content string into specifies file path.
  9. // It automatically creates directory recursively if it does not exist.
  10. gfile.PutContents(tempFile, "goframe example content")
  11. // read contents
  12. fmt.Println(gfile.GetContents(tempFile))
  13. // Output:
  14. // goframe example content
  15. }

PutBytes

  • Description: Writes bytes to the specified file path. If the file does not exist, it will be created recursively.
  • Format:
  1. func PutBytes(path string, content []byte) error
  • Example:
  1. func ExamplePutBytes() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutBytes(tempFile, []byte("goframe example content"))
  10. // read contents
  11. fmt.Println(gfile.GetContents(tempFile))
  12. // Output:
  13. // goframe example content
  14. }

PutContentsAppend

  • Description: Appends string content to the specified file. If the file does not exist, it will be created recursively.
  • Format:
  1. func PutContentsAppend(path string, content string) error
  • Example:
  1. func ExamplePutContentsAppend() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // read contents
  11. fmt.Println(gfile.GetContents(tempFile))
  12. // It creates and append content string into specifies file path.
  13. // It automatically creates directory recursively if it does not exist.
  14. gfile.PutContentsAppend(tempFile, " append content")
  15. // read contents
  16. fmt.Println(gfile.GetContents(tempFile))
  17. // Output:
  18. // goframe example content
  19. // goframe example content append content
  20. }

PutBytesAppend

  • Description: Appends byte content to the specified file. If the file does not exist, it will be created recursively.
  • Format:
  1. func PutBytesAppend(path string, content []byte) error
  • Example:
  1. func ExamplePutBytesAppend() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // read contents
  11. fmt.Println(gfile.GetContents(tempFile))
  12. // write contents
  13. gfile.PutBytesAppend(tempFile, []byte(" append"))
  14. // read contents
  15. fmt.Println(gfile.GetContents(tempFile))
  16. // Output:
  17. // goframe example content
  18. // goframe example content append
  19. }

GetNextCharOffset

  • Description: Gets the index of the specified character from a certain offset in the file.
  • Format:
  1. func GetNextCharOffset(reader io.ReaderAt, char byte, start int64) int64
  • Example:
  1. func ExampleGetNextCharOffset() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. f, err := gfile.OpenWithFlagPerm(tempFile, os.O_RDONLY, DefaultPermOpen)
  11. defer f.Close()
  12. // read contents
  13. index := gfile.GetNextCharOffset(f, 'f', 0)
  14. fmt.Println(index)
  15. // Output:
  16. // 2
  17. }

GetNextCharOffsetByPath

  • Description: Gets the index of the specified character from a certain offset in the file.
  • Format:
  1. func GetNextCharOffsetByPath(path string, char byte, start int64) int64
  • Example:
  1. func ExampleGetNextCharOffsetByPath() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // read contents
  11. index := gfile.GetNextCharOffsetByPath(tempFile, 'f', 0)
  12. fmt.Println(index)
  13. // Output:
  14. // 2
  15. }

GetBytesTilCharByPath

  • Description: Reads the file content up to a specified character and returns the content as a byte slice.
  • Format:
  1. func GetBytesTilCharByPath(path string, char byte, start int64) ([]byte, int64)
  • Example:
  1. func ExampleGetBytesTilCharByPath() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // read contents
  11. fmt.Println(gfile.GetBytesTilCharByPath(tempFile, 'f', 0))
  12. // Output:
  13. // [103 111 102] 2
  14. }

GetBytesByTwoOffsetsByPath

  • Description: Reads the content of the specified file between two offsets and returns it as a byte slice.
  • Format:
  1. func GetBytesByTwoOffsetsByPath(path string, start int64, end int64) []byte
  • Example:
  1. func ExampleGetBytesByTwoOffsetsByPath() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // read contents
  11. fmt.Println(gfile.GetBytesByTwoOffsetsByPath(tempFile, 0, 7))
  12. // Output:
  13. // [103 111 102 114 97 109 101]
  14. }

ReadLines

  • Description: Reads file content line by line as a string.
  • Format:
  1. func ReadLines(file string, callback func(text string) error) error
  • Example:
  1. func ExampleReadLines() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "L1 goframe example content\nL2 goframe example content")
  10. // read contents
  11. gfile.ReadLines(tempFile, func(text string) error {
  12. // Process each line
  13. fmt.Println(text)
  14. return nil
  15. })
  16. // Output:
  17. // L1 goframe example content
  18. // L2 goframe example content
  19. }

ReadLinesBytes

  • Description: Reads file content line by line as bytes.
  • Format:
  1. func ReadLinesBytes(file string, callback func(bytes []byte) error) error
  • Example:
  1. func ExampleReadLinesBytes() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_content")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "L1 goframe example content\nL2 goframe example content")
  10. // read contents
  11. gfile.ReadLinesBytes(tempFile, func(bytes []byte) error {
  12. // Process each line
  13. fmt.Println(bytes)
  14. return nil
  15. })
  16. // Output:
  17. // [76 49 32 103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
  18. // [76 50 32 103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
  19. }

Truncate

  • Description: Truncates the file to the specified size.
  • Note: If the given file path is a symlink, it will modify the source file.
  • Format:
  1. func Truncate(path string, size int) error
  • Example:
  1. func ExampleTruncate(){
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Check whether the `path` size
  7. stat, _ := gfile.Stat(path)
  8. fmt.Println(stat.Size())
  9. // Truncate file
  10. gfile.Truncate(path, 0)
  11. // Check whether the `path` size
  12. stat, _ = gfile.Stat(path)
  13. fmt.Println(stat.Size())
  14. // Output:
  15. // 13
  16. // 0
  17. }

Content Replacement

ReplaceFile

  • Description: Replaces specified content in the file with new content.
  • Format:
  1. func ReplaceFile(search, replace, path string) error
  • Example:
  1. func ExampleReplaceFile() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_replace")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // read contents
  11. fmt.Println(gfile.GetContents(tempFile))
  12. // It replaces content directly by file path.
  13. gfile.ReplaceFile("content", "replace word", tempFile)
  14. fmt.Println(gfile.GetContents(tempFile))
  15. // Output:
  16. // goframe example content
  17. // goframe example replace word
  18. }

ReplaceFileFunc

  • Description: Replaces the content of the specified file using a custom function.
  • Format:
  1. func ReplaceFileFunc(f func(path, content string) string, path string) error
  • Example:
  1. func ExampleReplaceFileFunc() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_replace")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example 123")
  10. // read contents
  11. fmt.Println(gfile.GetContents(tempFile))
  12. // It replaces content directly by file path and callback function.
  13. gfile.ReplaceFileFunc(func(path, content string) string {
  14. // Replace with regular match
  15. reg, _ := regexp.Compile(`\d{3}`)
  16. return reg.ReplaceAllString(content, "[num]")
  17. }, tempFile)
  18. fmt.Println(gfile.GetContents(tempFile))
  19. // Output:
  20. // goframe example 123
  21. // goframe example [num]
  22. }

ReplaceDir

  • Description: Scans the specified directory and replaces the specified content in matching files with new content.
  • Format:
  1. func ReplaceDir(search, replace, path, pattern string, recursive ...bool) error
  • Example:
  1. func ExampleReplaceDir() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_replace")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // read contents
  11. fmt.Println(gfile.GetContents(tempFile))
  12. // It replaces content of all files under specified directory recursively.
  13. gfile.ReplaceDir("content", "replace word", tempDir, "gfile_example.txt", true)
  14. // read contents
  15. fmt.Println(gfile.GetContents(tempFile))
  16. // Output:
  17. // goframe example content
  18. // goframe example replace word
  19. }

ReplaceDirFunc

  • Description: Scans the specified directory and uses a custom function to replace the specified content in matching files with new content.
  • Format:
  1. func ReplaceDirFunc(f func(path, content string) string, path, pattern string, recursive ...bool) error
  • Example:
  1. func ExampleReplaceDirFunc() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_replace")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example 123")
  10. // read contents
  11. fmt.Println(gfile.GetContents(tempFile))
  12. // It replaces content of all files under specified directory with custom callback function recursively.
  13. gfile.ReplaceDirFunc(func(path, content string) string {
  14. // Replace with regular match
  15. reg, _ := regexp.Compile(`\d{3}`)
  16. return reg.ReplaceAllString(content, "[num]")
  17. }, tempDir, "gfile_example.txt", true)
  18. fmt.Println(gfile.GetContents(tempFile))
  19. // Output:
  20. // goframe example 123
  21. // goframe example [num]
  22. }

File Time

MTime

  • Description: Gets the modification time of the path.
  • Format:
  1. func MTime(path string) time.Time
  • Example:
  1. func ExampleMTime() {
  2. t := gfile.MTime(gfile.TempDir())
  3. fmt.Println(t)
  4. // May Output:
  5. // 2021-11-02 15:18:43.901141 +0800 CST
  6. }

MTimestamp

  • Description: Gets the modification timestamp (seconds) of the path.
  • Format:
  1. func MTimestamp(path string) int64
  • Example:
  1. func ExampleMTimestamp() {
  2. t := gfile.MTimestamp(gfile.TempDir())
  3. fmt.Println(t)
  4. // May Output:
  5. // 1635838398
  6. }

MTimestampMilli

  • Description: Gets the modification timestamp (milliseconds) of the path.
  • Format:
  1. func MTimestampMilli(path string) int64
  • Example:
  1. func ExampleMTimestampMilli() {
  2. t := gfile.MTimestampMilli(gfile.TempDir())
  3. fmt.Println(t)
  4. // May Output:
  5. // 1635838529330
  6. }

File Size

Size

  • Description: Gets the size of the path without formatting.
  • Format:
  1. func Size(path string) int64
  • Example:
  1. func ExampleSize() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_size")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "0123456789")
  10. fmt.Println(gfile.Size(tempFile))
  11. // Output:
  12. // 10
  13. }

SizeFormat

  • Description: Gets the size of the path and formats it as a disk capacity.
  • Format:
  1. func SizeFormat(path string) string
  • Example:
  1. func ExampleSizeFormat() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_size")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "0123456789")
  10. fmt.Println(gfile.SizeFormat(tempFile))
  11. // Output:
  12. // 10.00B
  13. }

ReadableSize

  • Description: Gets the capacity size of the given path and formats it in a human-readable disk capacity format.
  • Format:
  1. func ReadableSize(path string) string
  • Example:
  1. func ExampleReadableSize() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_size")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "01234567899876543210")
  10. fmt.Println(gfile.ReadableSize(tempFile))
  11. // Output:
  12. // 20.00B
  13. }

StrToSize

  • Description: Converts a disk capacity size string to a size integer.
  • Format:
  1. func StrToSize(sizeStr string) int64
  • Example:
  1. func ExampleStrToSize() {
  2. size := gfile.StrToSize("100MB")
  3. fmt.Println(size)
  4. // Output:
  5. // 104857600
  6. }

FormatSize

  • Description: Converts a size integer to a disk capacity size string using K, m, g, t, p, e, b.
  • Format:
  1. func FormatSize(raw int64) string
  • Example:
  1. func ExampleFormatSize() {
  2. sizeStr := gfile.FormatSize(104857600)
  3. fmt.Println(sizeStr)
  4. sizeStr0 := gfile.FormatSize(1024)
  5. fmt.Println(sizeStr0)
  6. sizeStr1 := gfile.FormatSize(999999999999999999)
  7. fmt.Println(sizeStr1)
  8. // Output:
  9. // 100.00M
  10. // 1.00K
  11. // 888.18P
  12. }

File Sorting

SortFiles

  • Description: Sorts multiple paths alphabetically, with numbers taking precedence.
  • Format:
  1. func SortFiles(files []string) []string
  • Example:
  1. func ExampleSortFiles() {
  2. files := []string{
  3. "/aaa/bbb/ccc.txt",
  4. "/aaa/bbb/",
  5. "/aaa/",
  6. "/aaa",
  7. "/aaa/ccc/ddd.txt",
  8. "/bbb",
  9. "/0123",
  10. "/ddd",
  11. "/ccc",
  12. }
  13. sortOut := gfile.SortFiles(files)
  14. fmt.Println(sortOut)
  15. // Output:
  16. // [/0123 /aaa /aaa/ /aaa/bbb/ /aaa/bbb/ccc.txt /aaa/ccc/ddd.txt /bbb /ccc /ddd]
  17. }

Search

  • Description: Searches for files in the specified directory (default includes the current directory, execution directory, and main function directory; does not recurse subdirectories) and returns the real path.
  • Format:
  1. func Search(name string, prioritySearchPaths ...string) (realPath string, err error)
  • Example:
  1. func ExampleSearch() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_search")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. )
  8. // write contents
  9. gfile.PutContents(tempFile, "goframe example content")
  10. // search file
  11. realPath, _ := gfile.Search(fileName, tempDir)
  12. fmt.Println(gfile.Basename(realPath))
  13. // Output:
  14. // gfile_example.txt
  15. }

Directory Scanning

ScanDir

  • Description: Scans the specified directory and can scan files or directories, supporting recursive scans.
  • Format:
  1. func ScanDir(path string, pattern string, recursive ...bool) ([]string, error)
  • Example:
  1. func ExampleScanDir() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_scan_dir")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. tempSubDir = gfile.Join(tempDir, "sub_dir")
  8. tempSubFile = gfile.Join(tempSubDir, fileName)
  9. )
  10. // write contents
  11. gfile.PutContents(tempFile, "goframe example content")
  12. gfile.PutContents(tempSubFile, "goframe example content")
  13. // scans directory recursively
  14. list, _ := gfile.ScanDir(tempDir, "*", true)
  15. for _, v := range list {
  16. fmt.Println(gfile.Basename(v))
  17. }
  18. // Output:
  19. // gfile_example.txt
  20. // sub_dir
  21. // gfile_example.txt
  22. }

ScanDirFile

  • Description: Scans the files in the specified directory, supporting recursive scanning.
  • Format:
  1. func ScanDirFile(path string, pattern string, recursive ...bool) ([]string, error)
  • Example:
  1. func ExampleScanDirFile() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_scan_dir_file")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. tempSubDir = gfile.Join(tempDir, "sub_dir")
  8. tempSubFile = gfile.Join(tempSubDir, fileName)
  9. )
  10. // write contents
  11. gfile.PutContents(tempFile, "goframe example content")
  12. gfile.PutContents(tempSubFile, "goframe example content")
  13. // scans directory recursively exclusive of directories
  14. list, _ := gfile.ScanDirFile(tempDir, "*.txt", true)
  15. for _, v := range list {
  16. fmt.Println(gfile.Basename(v))
  17. }
  18. // Output:
  19. // gfile_example.txt
  20. // gfile_example.txt
  21. }

ScanDirFunc

  • Description: Scans the specified directory (with custom filtering method), can scan files or directories, and supports recursive scans.
  • Format:
  1. func ScanDirFunc(path string, pattern string, recursive bool, handler func(path string) string) ([]string, error)
  • Example:
  1. func ExampleScanDirFunc() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_scan_dir_func")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. tempSubDir = gfile.Join(tempDir, "sub_dir")
  8. tempSubFile = gfile.Join(tempSubDir, fileName)
  9. )
  10. // write contents
  11. gfile.PutContents(tempFile, "goframe example content")
  12. gfile.PutContents(tempSubFile, "goframe example content")
  13. // scans directory recursively
  14. list, _ := gfile.ScanDirFunc(tempDir, "*", true, func(path string) string {
  15. // ignores some files
  16. if gfile.Basename(path) == "gfile_example.txt" {
  17. return ""
  18. }
  19. return path
  20. })
  21. for _, v := range list {
  22. fmt.Println(gfile.Basename(v))
  23. }
  24. // Output:
  25. // sub_dir
  26. }

ScanDirFileFunc

  • Description: Scans the files in the specified directory (with custom filtering method), supporting recursive scans.
  • Format:
  1. func ScanDirFileFunc(path string, pattern string, recursive bool, handler func(path string) string) ([]string, error)
  • Example:
  1. func ExampleScanDirFileFunc() {
  2. // init
  3. var (
  4. fileName = "gfile_example.txt"
  5. tempDir = gfile.TempDir("gfile_example_scan_dir_file_func")
  6. tempFile = gfile.Join(tempDir, fileName)
  7. fileName1 = "gfile_example_ignores.txt"
  8. tempFile1 = gfile.Join(tempDir, fileName1)
  9. tempSubDir = gfile.Join(tempDir, "sub_dir")
  10. tempSubFile = gfile.Join(tempSubDir, fileName)
  11. )
  12. // write contents
  13. gfile.PutContents(tempFile, "goframe example content")
  14. gfile.PutContents(tempFile1, "goframe example content")
  15. gfile.PutContents(tempSubFile, "goframe example content")
  16. // scans directory recursively exclusive of directories
  17. list, _ := gfile.ScanDirFileFunc(tempDir, "*.txt", true, func(path string) string {
  18. // ignores some files
  19. if gfile.Basename(path) == "gfile_example_ignores.txt" {
  20. return ""
  21. }
  22. return path
  23. })
  24. for _, v := range list {
  25. fmt.Println(gfile.Basename(v))
  26. }
  27. // Output:
  28. // gfile_example.txt
  29. // gfile_example.txt
  30. }

Common Directories

Pwd

  • Description: Gets the current working path.
  • Format:
  1. func Pwd() string
  • Example:
  1. func ExamplePwd() {
  2. // Get absolute path of current working directory.
  3. fmt.Println(gfile.Pwd())
  4. // May Output:
  5. // xxx/gf/os/gfile
  6. }

Home

  • Description: Gets the home directory of the executing user.
  • Format:
  1. func Home(names ...string) (string, error)
  • Example:
  1. func ExampleHome() {
  2. // user's home directory
  3. homePath, _ := gfile.Home()
  4. fmt.Println(homePath)
  5. // May Output:
  6. // C:\Users\hailaz
  7. }

Temp

  • Description: Gets the absolute path after appending the system temporary path.

  • Format:

  1. func Temp(names ...string) string
  • Example:
  1. func ExampleTempDir() {
  2. // init
  3. var (
  4. fileName = "gfile_example_basic_dir"
  5. )
  6. // fetch an absolute representation of path.
  7. path := gfile.Temp(fileName)
  8. fmt.Println(path)
  9. // Output:
  10. // /tmp/gfile_example_basic_dir
  11. }

SelfPath

  • Description: Gets the absolute path of the current running program.

  • Format:

  1. func SelfPath() string
  • Example:
  1. func ExampleSelfPath() {
  2. // Get absolute file path of current running process
  3. fmt.Println(gfile.SelfPath())
  4. // May Output:
  5. // xxx/___github_com_gogf_gf_v2_os_gfile__ExampleSelfPath
  6. }

Type Judgment

IsDir

  • Description: Checks if the given path is a directory.
  • Format:
  1. func IsDir(path string) bool
  • Example:
  1. func ExampleIsDir() {
  2. // init
  3. var (
  4. path = gfile.TempDir("gfile_example_basic_dir")
  5. filePath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  6. )
  7. // Checks whether given `path` a directory.
  8. fmt.Println(gfile.IsDir(path))
  9. fmt.Println(gfile.IsDir(filePath))
  10. // Output:
  11. // true
  12. // false
  13. }

IsFile

  • Description: Checks if the given path is a file.
  • Format:
  1. func IsFile(path string) bool
  • Example:
  1. func ExampleIsFile() {
  2. // init
  3. var (
  4. filePath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. dirPath = gfile.TempDir("gfile_example_basic_dir")
  6. )
  7. // Checks whether given `path` a file, which means it's not a directory.
  8. fmt.Println(gfile.IsFile(filePath))
  9. fmt.Println(gfile.IsFile(dirPath))
  10. // Output:
  11. // true
  12. // false
  13. }

Permission Operations

IsReadable

  • Description: Checks if the given path is readable.

  • Format:

  1. func IsReadable(path string) bool
  • Example:
  1. func ExampleIsReadable() {
  2. // init
  3. var (
  4. path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log"
  5. )
  6. // Checks whether given `path` is readable.
  7. fmt.Println(gfile.IsReadable(path))
  8. // Output:
  9. // true
  10. }

IsWritable

  • Description: Checks if the specified path is writable. If the path is a directory, a temporary file is created to check if it is writable. If it is a file, it is checked if it can be opened.

  • Format:

  1. func IsWritable(path string) bool
  • Example:
  1. func ExampleIsWritable() {
  2. // init
  3. var (
  4. path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log"
  5. )
  6. // Checks whether given `path` is writable.
  7. fmt.Println(gfile.IsWritable(path))
  8. // Output:
  9. // true
  10. }

Chmod

  • Description: Changes the file permissions of the specified path to the specified permissions.

  • Format:

  1. func Chmod(path string, mode os.FileMode) error
  • Example:
  1. func ExampleChmod() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Get a FileInfo describing the named file.
  7. stat, err := gfile.Stat(path)
  8. if err != nil {
  9. fmt.Println(err.Error())
  10. }
  11. // Show original mode
  12. fmt.Println(stat.Mode())
  13. // Change file model
  14. gfile.Chmod(path, gfile.DefaultPermCopy)
  15. // Get a FileInfo describing the named file.
  16. stat, _ = gfile.Stat(path)
  17. // Show the modified mode
  18. fmt.Println(stat.Mode())
  19. // Output:
  20. // -rw-r--r--
  21. // -rwxrwxrwx
  22. }

File/Directory Operations

Mkdir

  • Description: Creates a directory, supporting recursive creation (absolute paths are recommended). The created directory permissions are: drwxr-xr-x.
  • Format:
  1. func Mkdir(path string) error
  • Example:
  1. func ExampleMkdir() {
  2. // init
  3. var (
  4. path = gfile.TempDir("gfile_example_basic_dir")
  5. )
  6. // Creates directory
  7. gfile.Mkdir(path)
  8. // Check if directory exists
  9. fmt.Println(gfile.IsDir(path))
  10. // Output:
  11. // true
  12. }

Create

  • Description: Creates a file/directory. If the directory in the path does not exist, it will automatically create the directory and file. The created file permissions are -rw-r–r–.
  • Note: If the created file already exists, it will clear the file’s content!
  • Format:
  1. func Create(path string) (*os.File, error)
  • Example:
  1. func ExampleCreate() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. dataByte = make([]byte, 50)
  6. )
  7. // Check whether the file exists
  8. isFile := gfile.IsFile(path)
  9. fmt.Println(isFile)
  10. // Creates file with given `path` recursively
  11. fileHandle, _ := gfile.Create(path)
  12. defer fileHandle.Close()
  13. // Write some content to file
  14. n, _ := fileHandle.WriteString("hello goframe")
  15. // Check whether the file exists
  16. isFile = gfile.IsFile(path)
  17. fmt.Println(isFile)
  18. // Reset file uintptr
  19. unix.Seek(int(fileHandle.Fd()), 0, 0)
  20. // Reads len(b) bytes from the File
  21. fileHandle.Read(dataByte)
  22. fmt.Println(string(dataByte[:n]))
  23. // Output:
  24. // false
  25. // true
  26. // hello goframe
  27. }

Open

  • Description: Opens a file/directory in read-only mode.
  • Format:
  1. func Open(path string) (*os.File, error)
  • Example:
  1. func ExampleOpen() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. dataByte = make([]byte, 4096)
  6. )
  7. // Open file or directory with READONLY model
  8. file, _ := gfile.Open(path)
  9. defer file.Close()
  10. // Read data
  11. n, _ := file.Read(dataByte)
  12. fmt.Println(string(dataByte[:n]))
  13. // Output:
  14. // hello goframe
  15. }

OpenFile

  • Description: Opens a file/directory with the specified flag and perm.
  • Format:
  1. func OpenFile(path string, flag int, perm os.FileMode) (*os.File, error)
  • Example:
  1. func ExampleOpenFile() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. dataByte = make([]byte, 4096)
  6. )
  7. // Opens file/directory with custom `flag` and `perm`
  8. // Create if file does not exist,it is created in a readable and writable mode,prem 0777
  9. openFile, _ := gfile.OpenFile(path, os.O_CREATE|os.O_RDWR, gfile.DefaultPermCopy)
  10. defer openFile.Close()
  11. // Write some content to file
  12. writeLength, _ := openFile.WriteString("hello goframe test open file")
  13. fmt.Println(writeLength)
  14. // Read data
  15. unix.Seek(int(openFile.Fd()), 0, 0)
  16. n, _ := openFile.Read(dataByte)
  17. fmt.Println(string(dataByte[:n]))
  18. // Output:
  19. // 28
  20. // hello goframe test open file
  21. }

OpenWithFalg

  • Description: Opens a file/directory with the specified flag.
  • Format:
  1. func OpenWithFlag(path string, flag int) (*os.File, error)
  • Example:
  1. func ExampleOpenWithFlag() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. dataByte = make([]byte, 4096)
  6. )
  7. // Opens file/directory with custom `flag`
  8. // Create if file does not exist,it is created in a readable and writable mode with default `perm` is 0666
  9. openFile, _ := gfile.OpenWithFlag(path, os.O_CREATE|os.O_RDWR)
  10. defer openFile.Close()
  11. // Write some content to file
  12. writeLength, _ := openFile.WriteString("hello goframe test open file with flag")
  13. fmt.Println(writeLength)
  14. // Read data
  15. unix.Seek(int(openFile.Fd()), 0, 0)
  16. n, _ := openFile.Read(dataByte)
  17. fmt.Println(string(dataByte[:n]))
  18. // Output:
  19. // 38
  20. // hello goframe test open file with flag
  21. }

OpenWithFalgPerm

  • Description: Opens a file/directory with the specified flag and perm.
  • Format:
  1. func OpenWithFlagPerm(path string, flag int, perm os.FileMode) (*os.File, error)
  • Example:
  1. func ExampleOpenWithFlagPerm() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. dataByte = make([]byte, 4096)
  6. )
  7. // Opens file/directory with custom `flag` and `perm`
  8. // Create if file does not exist,it is created in a readable and writable mode with `perm` is 0777
  9. openFile, _ := gfile.OpenWithFlagPerm(path, os.O_CREATE|os.O_RDWR, gfile.DefaultPermCopy)
  10. defer openFile.Close()
  11. // Write some content to file
  12. writeLength, _ := openFile.WriteString("hello goframe test open file with flag and perm")
  13. fmt.Println(writeLength)
  14. // Read data
  15. unix.Seek(int(openFile.Fd()), 0, 0)
  16. n, _ := openFile.Read(dataByte)
  17. fmt.Println(string(dataByte[:n]))
  18. // Output:
  19. // 38
  20. // hello goframe test open file with flag
  21. }

Stat

  • Description: Gets the file information of the given path.
  • Format:
  1. func Stat(path string) (os.FileInfo, error)
  • Example:
  1. func ExampleStat() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Get a FileInfo describing the named file.
  7. stat, _ := gfile.Stat(path)
  8. fmt.Println(stat.Name())
  9. fmt.Println(stat.IsDir())
  10. fmt.Println(stat.Mode())
  11. fmt.Println(stat.ModTime())
  12. fmt.Println(stat.Size())
  13. fmt.Println(stat.Sys())
  14. // May Output:
  15. // file1
  16. // false
  17. // -rwxr-xr-x
  18. // 2021-12-02 11:01:27.261441694 +0800 CST
  19. // &{16777220 33261 1 8597857090 501 20 0 [0 0 0 0] {1638414088 192363490} {1638414087 261441694} {1638414087 261441694} {1638413480 485068275} 38 8 4096 0 0 0 [0 0]}
  20. }

Copy

  • Description: Supports copying files or directories.
  • Format:
  1. func Copy(src string, dst string) error
  • Example:
  1. func ExampleCopy() {
  2. // init
  3. var (
  4. srcFileName = "gfile_example.txt"
  5. srcTempDir = gfile.TempDir("gfile_example_copy_src")
  6. srcTempFile = gfile.Join(srcTempDir, srcFileName)
  7. // copy file
  8. dstFileName = "gfile_example_copy.txt"
  9. dstTempFile = gfile.Join(srcTempDir, dstFileName)
  10. // copy dir
  11. dstTempDir = gfile.TempDir("gfile_example_copy_dst")
  12. )
  13. // write contents
  14. gfile.PutContents(srcTempFile, "goframe example copy")
  15. // copy file
  16. gfile.Copy(srcTempFile, dstTempFile)
  17. // read contents after copy file
  18. fmt.Println(gfile.GetContents(dstTempFile))
  19. // copy dir
  20. gfile.Copy(srcTempDir, dstTempDir)
  21. // list copy dir file
  22. fList, _ := gfile.ScanDir(dstTempDir, "*", false)
  23. for _, v := range fList {
  24. fmt.Println(gfile.Basename(v))
  25. }
  26. // Output:
  27. // goframe example copy
  28. // gfile_example.txt
  29. // gfile_example_copy.txt
  30. }

CopyFile

  • Description: Copies a file.
  • Format:
  1. func CopyFile(src, dst string) (err error)
  • Example:
  1. func ExampleCopyFile() {
  2. // init
  3. var (
  4. srcFileName = "gfile_example.txt"
  5. srcTempDir = gfile.TempDir("gfile_example_copy_src")
  6. srcTempFile = gfile.Join(srcTempDir, srcFileName)
  7. // copy file
  8. dstFileName = "gfile_example_copy.txt"
  9. dstTempFile = gfile.Join(srcTempDir, dstFileName)
  10. )
  11. // write contents
  12. gfile.PutContents(srcTempFile, "goframe example copy")
  13. // copy file
  14. gfile.CopyFile(srcTempFile, dstTempFile)
  15. // read contents after copy file
  16. fmt.Println(gfile.GetContents(dstTempFile))
  17. // Output:
  18. // goframe example copy
  19. }

CopyDir

  • Description: Supports copying files or directories.
  • Format:
  1. func CopyDir(src string, dst string) error
  • Example:
  1. func ExampleCopyDir() {
  2. // init
  3. var (
  4. srcTempDir = gfile.TempDir("gfile_example_copy_src")
  5. // copy file
  6. dstFileName = "gfile_example_copy.txt"
  7. dstTempFile = gfile.Join(srcTempDir, dstFileName)
  8. // copy dir
  9. dstTempDir = gfile.TempDir("gfile_example_copy_dst")
  10. )
  11. // read contents after copy file
  12. fmt.Println(gfile.GetContents(dstTempFile))
  13. // copy dir
  14. gfile.CopyDir(srcTempDir, dstTempDir)
  15. // list copy dir file
  16. fList, _ := gfile.ScanDir(dstTempDir, "*", false)
  17. for _, v := range fList {
  18. fmt.Println(gfile.Basename(v))
  19. }
  20. // Output:
  21. // gfile_example.txt
  22. // gfile_example_copy.txt
  23. }

Move

  • Description: Renames src to dst.

  • Note: If dst already exists and is a file, it will be replaced, potentially causing data loss.

  • Format:

  1. func Move(src string, dst string) error
  • Example:
  1. func ExampleMove() {
  2. // init
  3. var (
  4. srcPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. dstPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file2")
  6. )
  7. // Check is file
  8. fmt.Println(gfile.IsFile(dstPath))
  9. // Moves `src` to `dst` path.
  10. // If `dst` already exists and is not a directory, it'll be replaced.
  11. gfile.Move(srcPath, dstPath)
  12. fmt.Println(gfile.IsFile(srcPath))
  13. fmt.Println(gfile.IsFile(dstPath))
  14. // Output:
  15. // false
  16. // false
  17. // true
  18. }

Rename

  • Description: Alias for Move, renames src to dst.

  • Note: If dst already exists and is a file, it will be replaced, potentially causing data loss.

  • Format:

  1. func Rename(src string, dst string) error
  • Example:
  1. func ExampleRename() {
  2. // init
  3. var (
  4. srcPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file2")
  5. dstPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  6. )
  7. // Check is file
  8. fmt.Println(gfile.IsFile(dstPath))
  9. // renames (moves) `src` to `dst` path.
  10. // If `dst` already exists and is not a directory, it'll be replaced.
  11. gfile.Rename(srcPath, dstPath)
  12. fmt.Println(gfile.IsFile(srcPath))
  13. fmt.Println(gfile.IsFile(dstPath))
  14. // Output:
  15. // false
  16. // false
  17. // true
  18. }

Remove

  • Description: Deletes the file or directory at the given path.

  • Format:

  1. func Remove(path string) error
  • Example:
  1. func ExampleRemove() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Checks whether given `path` a file, which means it's not a directory.
  7. fmt.Println(gfile.IsFile(path))
  8. // deletes all file/directory with `path` parameter.
  9. gfile.Remove(path)
  10. // Check again
  11. fmt.Println(gfile.IsFile(path))
  12. // Output:
  13. // true
  14. // false
  15. }

IsEmpty

  • Description: Checks if the given path is empty, if a directory, checks if it contains files; if a file, checks if the file size is empty.

  • Format:

  1. func IsEmpty(path string) bool
  • Example:
  1. func ExampleIsEmpty() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Check whether the `path` is empty
  7. fmt.Println(gfile.IsEmpty(path))
  8. // Truncate file
  9. gfile.Truncate(path, 0)
  10. // Check whether the `path` is empty
  11. fmt.Println(gfile.IsEmpty(path))
  12. // Output:
  13. // false
  14. // true
  15. }

DirNames

  • Description: Gets the list of files under the given path and returns them as a slice.

  • Format:

  1. func DirNames(path string) ([]string, error)
  • Example:
  1. func ExampleDirNames() {
  2. // init
  3. var (
  4. path = gfile.TempDir("gfile_example_basic_dir")
  5. )
  6. // Get sub-file names of given directory `path`.
  7. dirNames, _ := gfile.DirNames(path)
  8. fmt.Println(dirNames)
  9. // May Output:
  10. // [file1]
  11. }

Glob

  • Description: Fuzzy search for the file list under the given path, supports regex, the second parameter controls whether to return the results with absolute paths.

  • Format:

  1. func Glob(pattern string, onlyNames ...bool) ([]string, error)
  • Example:
  1. func ExampleGlob() {
  2. // init
  3. var (
  4. path = gfile.Pwd() + gfile.Separator + "*_example_basic_test.go"
  5. )
  6. // Get sub-file names of given directory `path`.
  7. // Only show file name
  8. matchNames, _ := gfile.Glob(path, true)
  9. fmt.Println(matchNames)
  10. // Show full path of the file
  11. matchNames, _ = gfile.Glob(path, false)
  12. fmt.Println(matchNames)
  13. // May Output:
  14. // [gfile_z_example_basic_test.go]
  15. // [xxx/gf/os/gfile/gfile_z_example_basic_test.go]
  16. }

Exists

  • Description: Checks if the given path exists.
  • Format:
  1. func Exists(path string) bool
  • Example:
  1. func ExampleExists() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Checks whether given `path` exist.
  7. fmt.Println(gfile.Exists(path))
  8. // Output:
  9. // true
  10. }

Chdir

  • Description: Changes the current working path to the given path.
  • Format:
  1. func Chdir(dir string) error
  • Example:
  1. func ExampleChdir() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Get current working directory
  7. fmt.Println(gfile.Pwd())
  8. // Changes the current working directory to the named directory.
  9. gfile.Chdir(path)
  10. // Get current working directory
  11. fmt.Println(gfile.Pwd())
  12. // May Output:
  13. // xxx/gf/os/gfile
  14. // /tmp/gfile_example_basic_dir/file1
  15. }

Path Operations

Join

  • Description: Joins multiple string paths with /.
  • Format:
  1. func Join(paths ...string) string
  • Example:
  1. func ExampleJoin() {
  2. // init
  3. var (
  4. dirPath = gfile.TempDir("gfile_example_basic_dir")
  5. filePath = "file1"
  6. )
  7. // Joins string array paths with file separator of current system.
  8. joinString := gfile.Join(dirPath, filePath)
  9. fmt.Println(joinString)
  10. // Output:
  11. // /tmp/gfile_example_basic_dir/file1
  12. }

Abs

  • Description: Returns the absolute path of the given path.

  • Format:

  1. func Abs(path string) string
  • Example:
  1. func ExampleAbs() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Get an absolute representation of path.
  7. fmt.Println(gfile.Abs(path))
  8. // Output:
  9. // /tmp/gfile_example_basic_dir/file1
  10. }

RealPath

  • Description: Gets the absolute path of the given path.

  • Note: Returns empty if the file does not exist.

  • Format:

  1. func RealPath(path string) string
  • Example:
  1. func ExampleRealPath() {
  2. // init
  3. var (
  4. realPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. worryPath = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "worryFile")
  6. )
  7. // fetch an absolute representation of path.
  8. fmt.Println(gfile.RealPath(realPath))
  9. fmt.Println(gfile.RealPath(worryPath))
  10. // Output:
  11. // /tmp/gfile_example_basic_dir/file1
  12. //
  13. }

SelfName

  • Description: Gets the name of the current running program.

  • Format:

  1. func SelfName() string
  • Example:
  1. func ExampleSelfName() {
  2. // Get file name of current running process
  3. fmt.Println(gfile.SelfName())
  4. // May Output:
  5. // ___github_com_gogf_gf_v2_os_gfile__ExampleSelfName
  6. }

Basename

  • Description: Gets the last element of the given path, including the extension.

  • Format:

  1. func Basename(path string) string
  • Example:
  1. func ExampleBasename() {
  2. // init
  3. var (
  4. path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log"
  5. )
  6. // Get the last element of path, which contains file extension.
  7. fmt.Println(gfile.Basename(path))
  8. // Output:
  9. // file.log
  10. }

Name

  • Description: Gets the last element of the given path, excluding the extension.

  • Format:

  1. func Name(path string) string
  • Example:
  1. func ExampleName() {
  2. // init
  3. var (
  4. path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log"
  5. )
  6. // Get the last element of path without file extension.
  7. fmt.Println(gfile.Name(path))
  8. // Output:
  9. // file
  10. }

Dir

  • Description: Gets the directory part of the given path, excluding the last element.

  • Format:

  1. func Dir(path string) string
  • Example:
  1. func ExampleDir() {
  2. // init
  3. var (
  4. path = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
  5. )
  6. // Get all but the last element of path, typically the path's directory.
  7. fmt.Println(gfile.Dir(path))
  8. // Output:
  9. // /tmp/gfile_example_basic_dir
  10. }

Ext

  • Description: Gets the extension of the given path, including ..

  • Format:

  1. func Ext(path string) string
  • Example:
  1. func ExampleExt() {
  2. // init
  3. var (
  4. path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log"
  5. )
  6. // Get the file name extension used by path.
  7. fmt.Println(gfile.Ext(path))
  8. // Output:
  9. // .log
  10. }

ExtName

  • Description: Gets the extension of the given path, excluding ..

  • Format:

  1. func ExtName(path string) string
  • Example:
  1. func ExampleExtName() {
  2. // init
  3. var (
  4. path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log"
  5. )
  6. // Get the file name extension used by path but the result does not contains symbol '.'.
  7. fmt.Println(gfile.ExtName(path))
  8. // Output:
  9. // log
  10. }

MainPkgPath

  • Description: Gets the absolute path of the main file (entry point) location.

  • Note:

    • This method is only available in the development environment and is only effective in the source code development environment. It will display the source code path after building the binary.
    • If the method is called for the first time in an asynchronous goroutine, it may not be able to get the path of the main package.
  • Format:
  1. func MainPkgPath() string
  • Example:
  1. func Test() {
  2. fmt.Println("main pkg path on main :", gfile.MainPkgPath())
  3. char := make(chan int, 1)
  4. go func() {
  5. fmt.Println("main pkg path on goroutine :", gfile.MainPkgPath())
  6. char <- 1
  7. }()
  8. select {
  9. case <-char:
  10. }
  11. // Output:
  12. // /xxx/xx/xxx/xx
  13. // /xxx/xx/xxx/xx
  14. }
  15. // Binary package
  16. $ ./testDemo
  17. main pkg path on main : /xxx/xx/xxx/xx
  18. main pkg path on goroutine : /xxx/xx/xxx/xx