KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Retrieving the extension of a file
PRODUCT: 4D | VERSION: 2003.3 | PLATFORM: Mac & Win
Published On: April 29, 2004

Compatibility: Version 6.8.x and 2003.x

When manipulating files in 4D, you might come across a problem where you want to perform some action only on certain types of files. In this case, you will have to be able to accurately identify the extension of a file. Filenames can contain periods in them, so it is not safe to assume that the extension of a file is immediately after a period in the filename.

For example, the extension of "myfile.old.txt" is "txt" not ".old.txt." The following method correctly extracts the extension of a filename and either returns the extension or null string if there is no extension.

C_TEXT($1;$fileName)
C_TEXT($0;$ext)
C_STRING(1;$char)
C_LONGINT($len)

$fileName:=$1
$len:=Length($fileName)

  ` find the position of the last period
If (Position(".";$fileName)#0)
  While (($len>0) & ($char#"."))

    $char:=Substring($fileName;$len;1)

    If($char#".")
      $ext:=$char+$ext
    End if

    $len:=$len-1

  End while
End if

$0:=$ext