diff --git a/file.go b/file.go index bf557b3..334938a 100644 --- a/file.go +++ b/file.go @@ -94,6 +94,21 @@ func TrimFileName(ppath string) string { return `` } +func BaseFileName(ppath string) string { + if len(ppath) == 0 { + return ppath + } + for i := len(ppath) - 1; i >= 0; i-- { + if ppath[i] == '/' || ppath[i] == '\\' { + if i+1 < len(ppath) { + return ppath[i+1:] + } + return BaseFileName(ppath[0:i]) + } + } + return ppath +} + // FileSize returns file size in bytes and possible error. func FileSize(file string) (int64, error) { f, err := os.Stat(file) diff --git a/file_test.go b/file_test.go index 563932d..fc1dbec 100644 --- a/file_test.go +++ b/file_test.go @@ -43,3 +43,14 @@ func TestFileIsCompleted(t *testing.T) { wg.Wait() } + +func TestBaseFileName(t *testing.T) { + r := BaseFileName(`abc/dd.txt`) + assert.Equal(t, `dd.txt`, r) + r = BaseFileName(`abc\dd.txt`) + assert.Equal(t, `dd.txt`, r) + r = BaseFileName(`abc\dd.txt/`) + assert.Equal(t, `dd.txt`, r) + r = BaseFileName(`/`) + assert.Equal(t, ``, r) +}