basename Function

private elemental function basename(self, sep, extension, strip_last_extension)

Arguments

TypeIntentOptionalAttributesName
class(string), intent(in) :: self
character(kind=CK,len=*), intent(in), optional :: sep
character(kind=CK,len=*), intent(in), optional :: extension
logical, intent(in), optional :: strip_last_extension

Return Value type(string)


Contents

Source Code


Source Code

   elemental function basename(self, sep, extension, strip_last_extension)
   !< Return the base file name of a string containing a file name.
   !<
   !< Optionally, the extension is also stripped if provided or the last one if required, e.g.
   !<
   !<```fortran
   !< type(string) :: astring
   !< logical      :: test_passed(5)
   !< astring = 'bar/foo.tar.bz2'
   !< test_passed(1) = astring%basename()//''=='foo.tar.bz2'
   !< test_passed(2) = astring%basename(extension='.tar.bz2')//''=='foo'
   !< test_passed(3) = astring%basename(strip_last_extension=.true.)//''=='foo.tar'
   !< astring = '\bar\foo.tar.bz2'
   !< test_passed(4) = astring%basename(sep='\')//''=='foo.tar.bz2'
   !< astring = 'bar'
   !< test_passed(5) = astring%basename(strip_last_extension=.true.)//''=='bar'
   !< print '(L1)', all(test_passed)
   !<```
   !=> T <<<
   class(string),             intent(in)           :: self                 !< The string.
   character(kind=CK, len=*), intent(in), optional :: sep                  !< Directory separator.
   character(kind=CK, len=*), intent(in), optional :: extension            !< File extension.
   logical,                   intent(in), optional :: strip_last_extension !< Flag to enable the stripping of last extension.
   type(string)                                    :: basename             !< Base file name.
   character(kind=CK, len=:), allocatable          :: sep_                 !< Separator, default value.
   integer                                         :: pos                  !< Character position.

   if (allocated(self%raw)) then
      sep_ = UIX_DIR_SEP ; if (present(sep)) sep_ = sep
      basename = self
      pos = index(basename%raw, sep_, back=.true.)
      if (pos>0) basename%raw = self%raw(pos+1:)
      if (present(extension)) then
         pos = index(basename%raw, extension, back=.true.)
         if (pos>0) basename%raw = basename%raw(1:pos-1)
      elseif (present(strip_last_extension)) then
         if (strip_last_extension) then
            pos = index(basename%raw, '.', back=.true.)
            if (pos>0) basename%raw = basename%raw(1:pos-1)
         endif
      endif
   endif
   endfunction basename