DOKK / manpages / debian 10 / erlang-manpages / filename.3erl.en
filename(3erl) Erlang Module Definition filename(3erl)

filename - Filename manipulation functions.

This module provides functions for analyzing and manipulating filenames. These functions are designed so that the Erlang code can work on many different platforms with different filename formats. With filename is meant all strings that can be used to denote a file. The filename can be a short relative name like foo.erl, a long absolute name including a drive designator, a directory name like D:\usr/local\bin\erl/lib\tools\foo.erl, or any variations in between.

In Windows, all functions return filenames with forward slashes only, even if the arguments contain backslashes. To normalize a filename by removing redundant directory separators, use join/1.

The module supports raw filenames in the way that if a binary is present, or the filename cannot be interpreted according to the return value of file:native_name_encoding/0, a raw filename is also returned. For example, join/1 provided with a path component that is a binary (and cannot be interpreted under the current native filename encoding) results in a raw filename that is returned (the join operation is performed of course). For more information about raw filenames, see the file module.

Note:
Functionality in this module generally assumes valid input and does not necessarily fail on input that does not use a valid encoding, but may instead very likely produce invalid output.

File operations used to accept filenames containing null characters (integer value zero). This caused the name to be truncated and in some cases arguments to primitive operations to be mixed up. Filenames containing null characters inside the filename are now rejected and will cause primitive file operations to fail.

Warning:
Currently null characters at the end of the filename will be accepted by primitive file operations. Such filenames are however still documented as invalid. The implementation will also change in the future and reject such filenames.


absname(Filename) -> file:filename_all()


Types:

Filename = file:name_all()

Converts a relative Filename and returns an absolute name. No attempt is made to create the shortest absolute name, as this can give incorrect results on file systems that allow links.

Unix examples:

1> pwd().
"/usr/local"
2> filename:absname("foo").
"/usr/local/foo"
3> filename:absname("../x").
"/usr/local/../x"
4> filename:absname("/").
"/"

Windows examples:

1> pwd().
"D:/usr/local"
2> filename:absname("foo").
"D:/usr/local/foo"
3> filename:absname("../x").
"D:/usr/local/../x"
4> filename:absname("/").
"D:/"


absname(Filename, Dir) -> file:filename_all()


Types:

Filename = Dir = file:name_all()

Same as absname/1, except that the directory to which the filename is to be made relative is specified in argument Dir.


absname_join(Dir, Filename) -> file:filename_all()


Types:

Dir = Filename = file:name_all()

Joins an absolute directory with a relative filename. Similar to join/2, but on platforms with tight restrictions on raw filename length and no support for symbolic links (read: VxWorks), leading parent directory components in Filename are matched against trailing directory components in Dir so they can be removed from the result - minimizing its length.


basedir(PathType, Application) -> file:filename_all()



basedir(PathsType, Application) -> [file:filename_all()]


Types:

PathType = basedir_path_type()
PathsType = basedir_paths_type()
Application = string() | binary()
basedir_path_type() = 

user_cache | user_config | user_data | user_log

basedir_paths_type() = site_config | site_data

Equivalent to basedir(PathType, Application, #{}) or basedir(PathsType, Application, #{}).


basedir(PathType, Application, Opts) -> file:filename_all()



basedir(PathsType, Application, Opts) -> [file:filename_all()]


Types:

PathType = basedir_path_type()
PathsType = basedir_paths_type()
Application = string() | binary()
Opts = basedir_opts()
basedir_path_type() = 

user_cache | user_config | user_data | user_log

basedir_paths_type() = site_config | site_data

basedir_opts() = 

#{author => string() | binary(),
os => windows | darwin | linux,
version => string() | binary()}

Returns a suitable path, or paths, for a given type. If os is not set in Opts the function will default to the native option, that is 'linux', 'darwin' or 'windows', as understood by os:type/0. Anything not recognized as 'darwin' or 'windows' is interpreted as 'linux'.

The options 'author' and 'version' are only used with 'windows' option mode.

*
user_cache

The path location is intended for transient data files on a local machine.

On Linux: Respects the os environment variable XDG_CACHE_HOME.

1> filename:basedir(user_cache, "my_application", #{os=>linux}).
"/home/otptest/.cache/my_application"

1> filename:basedir(user_cache, "my_application", #{os=>darwin}).
"/home/otptest/Library/Caches/my_application"

1> filename:basedir(user_cache, "My App").
"c:/Users/otptest/AppData/Local/My App/Cache"
2> filename:basedir(user_cache, "My App").
"c:/Users/otptest/AppData/Local/My App/Cache"
3> filename:basedir(user_cache, "My App", #{author=>"Erlang"}).
"c:/Users/otptest/AppData/Local/Erlang/My App/Cache"
4> filename:basedir(user_cache, "My App", #{version=>"1.2"}).
"c:/Users/otptest/AppData/Local/My App/1.2/Cache"
5> filename:basedir(user_cache, "My App", #{author=>"Erlang",version=>"1.2"}).
"c:/Users/otptest/AppData/Local/Erlang/My App/1.2/Cache"
*
user_config

The path location is intended for persistent configuration files.

On Linux: Respects the os environment variable XDG_CONFIG_HOME.

2> filename:basedir(user_config, "my_application", #{os=>linux}).
"/home/otptest/.config/my_application"

2> filename:basedir(user_config, "my_application", #{os=>darwin}).
"/home/otptest/Library/Application Support/my_application"

1> filename:basedir(user_config, "My App").
"c:/Users/otptest/AppData/Roaming/My App"
2> filename:basedir(user_config, "My App", #{author=>"Erlang", version=>"1.2"}).
"c:/Users/otptest/AppData/Roaming/Erlang/My App/1.2"
*
user_data

The path location is intended for persistent data files.

On Linux: Respects the os environment variable XDG_DATA_HOME.

3> filename:basedir(user_data, "my_application", #{os=>linux}).
"/home/otptest/.local/my_application"

3> filename:basedir(user_data, "my_application", #{os=>darwin}).
"/home/otptest/Library/Application Support/my_application"

8> filename:basedir(user_data, "My App").
"c:/Users/otptest/AppData/Local/My App"
9> filename:basedir(user_data, "My App",#{author=>"Erlang",version=>"1.2"}).
"c:/Users/otptest/AppData/Local/Erlang/My App/1.2"
*
user_log

The path location is intended for transient log files on a local machine.

On Linux: Respects the os environment variable XDG_CACHE_HOME.

4> filename:basedir(user_log, "my_application", #{os=>linux}).
"/home/otptest/.cache/my_application/log"

4> filename:basedir(user_log, "my_application", #{os=>darwin}).
"/home/otptest/Library/Caches/my_application"

12> filename:basedir(user_log, "My App").
"c:/Users/otptest/AppData/Local/My App/Logs"
13> filename:basedir(user_log, "My App",#{author=>"Erlang",version=>"1.2"}).
"c:/Users/otptest/AppData/Local/Erlang/My App/1.2/Logs"
*
site_config

On Linux: Respects the os environment variable XDG_CONFIG_DIRS.

5> filename:basedir(site_data, "my_application", #{os=>linux}).
["/usr/local/share/my_application",

"/usr/share/my_application"] 6> os:getenv("XDG_CONFIG_DIRS"). "/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg" 7> filename:basedir(site_config, "my_application", #{os=>linux}). ["/etc/xdg/xdg-ubuntu/my_application",
"/usr/share/upstart/xdg/my_application",
"/etc/xdg/my_application"] 8> os:unsetenv("XDG_CONFIG_DIRS"). true 9> filename:basedir(site_config, "my_application", #{os=>linux}). ["/etc/xdg/my_application"]

5> filename:basedir(site_config, "my_application", #{os=>darwin}).
["/Library/Application Support/my_application"]
*
site_data

On Linux: Respects the os environment variable XDG_DATA_DIRS.

10> os:getenv("XDG_DATA_DIRS").
"/usr/share/ubuntu:/usr/share/gnome:/usr/local/share/:/usr/share/"
11> filename:basedir(site_data, "my_application", #{os=>linux}).
["/usr/share/ubuntu/my_application",

"/usr/share/gnome/my_application",
"/usr/local/share/my_application",
"/usr/share/my_application"] 12> os:unsetenv("XDG_DATA_DIRS"). true 13> filename:basedir(site_data, "my_application", #{os=>linux}). ["/usr/local/share/my_application",
"/usr/share/my_application"]

5> filename:basedir(site_data, "my_application", #{os=>darwin}).
["/Library/Application Support/my_application"]


basename(Filename) -> file:filename_all()


Types:

Filename = file:name_all()

Returns the last component of Filename, or Filename itself if it does not contain any directory separators.

Examples:

5> filename:basename("foo").
"foo"
6> filename:basename("/usr/foo").
"foo"
7> filename:basename("/").
[]


basename(Filename, Ext) -> file:filename_all()


Types:

Filename = Ext = file:name_all()

Returns the last component of Filename with extension Ext stripped. This function is to be used to remove a (possible) specific extension. To remove an existing extension when you are unsure which one it is, use rootname(basename(Filename)).

Examples:

8> filename:basename("~/src/kalle.erl", ".erl").
"kalle"
9> filename:basename("~/src/kalle.beam", ".erl").
"kalle.beam"
10> filename:basename("~/src/kalle.old.erl", ".erl").
"kalle.old"
11> filename:rootname(filename:basename("~/src/kalle.erl")).
"kalle"
12> filename:rootname(filename:basename("~/src/kalle.beam")).
"kalle"


dirname(Filename) -> file:filename_all()


Types:

Filename = file:name_all()

Returns the directory part of Filename.

Examples:

13> filename:dirname("/usr/src/kalle.erl").
"/usr/src"
14> filename:dirname("kalle.erl").
"."

5> filename:dirname("\\usr\\src/kalle.erl"). % Windows
"/usr/src"


extension(Filename) -> file:filename_all()


Types:

Filename = file:name_all()

Returns the file extension of Filename, including the period. Returns an empty string if no extension exists.

Examples:

15> filename:extension("foo.erl").
".erl"
16> filename:extension("beam.src/kalle").
[]


find_src(Beam) ->


{SourceFile, Options} | {error, {ErrorReason, Module}}



find_src(Beam, Rules) ->


{SourceFile, Options} | {error, {ErrorReason, Module}}


Types:

Beam = Module | Filename
Filename = atom() | string()
Rules = [{BinSuffix :: string(), SourceSuffix :: string()}]
Module = module()
SourceFile = string()
Options = [Option]
Option =
{i, Path :: string()} |
{outdir, Path :: string()} |
{d, atom()}
ErrorReason = non_existing | preloaded | interpreted

Finds the source filename and compiler options for a module. The result can be fed to compile:file/2 to compile the file again.

Warning:
This function is deprecated. Use filelib:find_source/1 instead for finding source files.

If possible, use the beam_lib(3erl) module to extract the compiler options and the abstract code format from the Beam file and compile that instead.

Argument Beam, which can be a string or an atom, specifies either the module name or the path to the source code, with or without extension ".erl". In either case, the module must be known by the code server, that is, code:which(Module) must succeed.

Rules describes how the source directory can be found when the object code directory is known. It is a list of tuples {BinSuffix, SourceSuffix} and is interpreted as follows: if the end of the directory name where the object is located matches BinSuffix, then the name created by replacing BinSuffix with SourceSuffix is expanded by calling filelib:wildcard/1. If a regular file is found among the matches, the function returns that location together with Options. Otherwise the next rule is tried, and so on.

Rules defaults to:

[{"", ""}, {"ebin", "src"}, {"ebin", "esrc"},

{"ebin", "src/*"}, {"ebin", "esrc/*"}]

The function returns {SourceFile, Options} if it succeeds. SourceFile is the absolute path to the source file without extension ".erl". Options includes the options that are necessary to recompile the file with compile:file/2, but excludes options such as report and verbose, which do not change the way code is generated. The paths in options {outdir, Path} and {i, Path} are guaranteed to be absolute.


flatten(Filename) -> file:filename_all()


Types:

Filename = file:name_all()

Converts a possibly deep list filename consisting of characters and atoms into the corresponding flat string filename.


join(Components) -> file:filename_all()


Types:

Components = [file:name_all()]

Joins a list of filename Components with directory separators. If one of the elements of Components includes an absolute path, such as "/xxx", the preceding elements, if any, are removed from the result.

The result is "normalized":

*
Redundant directory separators are removed.
*
In Windows, all directory separators are forward slashes and the drive letter is in lower case.

Examples:

17> filename:join(["/usr", "local", "bin"]).
"/usr/local/bin"
18> filename:join(["a/b///c/"]).
"a/b/c"

6> filename:join(["B:a\\b///c/"]). % Windows
"b:a/b/c"


join(Name1, Name2) -> file:filename_all()


Types:

Name1 = Name2 = file:name_all()

Joins two filename components with directory separators. Equivalent to join([Name1, Name2]).


nativename(Path) -> file:filename_all()


Types:

Path = file:name_all()

Converts Path to a form accepted by the command shell and native applications on the current platform. On Windows, forward slashes are converted to backward slashes. On all platforms, the name is normalized as done by join/1.

Examples:

19> filename:nativename("/usr/local/bin/"). % Unix
"/usr/local/bin"

7> filename:nativename("/usr/local/bin/"). % Windows
"\\usr\\local\\bin"


pathtype(Path) -> absolute | relative | volumerelative


Types:

Path = file:name_all()

Returns the path type, which is one of the following:

The path name refers to a specific file on a specific volume.

Unix example: /usr/local/bin

Windows example: D:/usr/local/bin

The path name is relative to the current working directory on the current volume.

Example: foo/bar, ../src

The path name is relative to the current working directory on a specified volume, or it is a specific file on the current working volume.

Windows example: D:bar.erl, /bar/foo.erl


rootname(Filename) -> file:filename_all()



rootname(Filename, Ext) -> file:filename_all()


Types:

Filename = Ext = file:name_all()

Removes a filename extension. rootname/2 works as rootname/1, except that the extension is removed only if it is Ext.

Examples:

20> filename:rootname("/beam.src/kalle").
/beam.src/kalle"
21> filename:rootname("/beam.src/foo.erl").
"/beam.src/foo"
22> filename:rootname("/beam.src/foo.erl", ".erl").
"/beam.src/foo"
23> filename:rootname("/beam.src/foo.beam", ".erl").
"/beam.src/foo.beam"


safe_relative_path(Filename) -> unsafe | SafeFilename


Types:

Filename = SafeFilename = file:name_all()

Sanitizes the relative path by eliminating ".." and "." components to protect against directory traversal attacks. Either returns the sanitized path name, or the atom unsafe if the path is unsafe. The path is considered unsafe in the following circumstances:

*
The path is not relative.
*
A ".." component would climb up above the root of the relative path.

Examples:

1> filename:safe_relative_path("dir/sub_dir/..").
"dir"
2> filename:safe_relative_path("dir/..").
[]
3> filename:safe_relative_path("dir/../..").
unsafe
4> filename:safe_relative_path("/abs/path").
unsafe


split(Filename) -> Components


Types:

Filename = file:name_all()
Components = [file:name_all()]

Returns a list whose elements are the path components of Filename.

Examples:

24> filename:split("/usr/local/bin").
["/","usr","local","bin"]
25> filename:split("foo/bar").
["foo","bar"]
26> filename:split("a:\\msdev\\include").
["a:/","msdev","include"]
stdlib 3.7.1 Ericsson AB