filelib(3)

πŸ“¦
version 29.0.6 Β· 3 versions
, in ubuntu stonking

πŸŽ€ NAME πŸŽ€

filelib β€” file utilities, like wildcard matching of filenames, and other little helpers that just get you πŸ’–

(yes bestie, you're on filelib(3), an Erlang Module Definition page, welcome, come in, sit down ✨)


✨ DESCRIPTION ✨

Okay so real talk: this module has utilities that live on a higher level than the file module does. file is down there doing the grunt work; filelib is up here being the main character 🫢

One thing though β€” this module does not support "raw" filenames (like, files whose names don't comply with the expected encoding). Those files simply get ignored by the functions in this module. Not skipped with a warning, not handled, ignored πŸ™ˆ

If you want the full lore on raw filenames, go read the file module.

NOTE: functionality in this module generally assumes valid input, and it does not necessarily fail on input that doesn't use a valid encoding β€” no, it may instead very likely produce invalid output. That's the vibe. πŸ’€ Also: file operations used to accept filenames containing null characters (integer value zero). That caused the name to be truncated, and in some cases arguments to primitive operations got mixed up. Filenames containing null characters inside the filename are now rejected, and will cause primitive file operations to fail. Periodt.
WARNING: as it stands right now, null characters at the end of the filename will be accepted by primitive file operations. Those filenames are still documented as invalid though. And the implementation is going to change in the future and reject them. So don't build your whole personality on that behavior, bestie 😭

πŸ¦‹ DATA TYPES πŸ¦‹

  • dirname() :: filename().
  • dirname_all() :: filename_all().
  • filename() :: file:name().
  • filename_all() :: file:name_all().
  • find_file_rule() :: {ObjDirSuffix :: string(), SrcDirSuffix :: string()}.
  • and the two-liner:
find_source_rule() ::
          {ObjExtension :: string(),
           SrcExtension :: string(),
           [find_file_rule()]}.

πŸ‘‘ FUNCTIONS πŸ‘‘

ensure_dir(Name) -> ok | {error, Reason}

ensure_dir(Name) -> ok | {error, Reason}
                    when
                        Name :: filename_all() | dirname_all(),
                        Reason :: file:posix().

Makes sure all the parent directories for the specified file or directory name Name exist, and it tries to create them if necessary. Iconic behavior, honestly.

Returns ok if all parent directories already exist or can be created. Returns {error, Reason} if some parent directory doesn't exist and can't be created. Simple as that πŸ’…

ensure_path(Path) -> ok | {error, Reason}

ensure_path(Path) -> ok | {error, Reason}
                     when Path :: dirname_all(), Reason :: file:posix().

Same energy as above: makes sure all the parent directories for the specified path Path exist, trying to create them if necessary.

But unlike ensure_dir/1, this one will attempt to create all path segments as a directory β€” including the last segment. She goes all the way πŸ”₯

Returns ok if all parent directories already exist or can be created. Returns {error, Reason} if some parent directory doesn't exist and can't be created.

file_size(Filename) -> non_neg_integer()

file_size(Filename) -> non_neg_integer()
                    when Filename :: filename_all().

Returns the size of the specified file. That's it, that's the function πŸŽ€

find_file/3

find_file(filename(), filename(), [find_file_rule()]) ->
                   {ok, filename()} | {error, not_found}.

Looks for a file of the given name by applying suffix rules to the given directory path.

For example, a rule {"ebin", "src"} means that if the directory path ends with "ebin", the corresponding path ending in "src" should be searched. Cute, right?

If Rules is left out or is an empty list, the default system rules are used. See also the Kernel application parameter source_search_rules.

find_source/1

find_source(filename()) -> {ok, filename()} | {error, not_found}.

Equivalent to find_source(Base, Dir), where Dir is filename:dirname(FilePath) and Base is filename:basename(FilePath).

find_source/3

find_source(filename(), filename(), [find_source_rule()]) ->
                     {ok, filename()} | {error, not_found}.

Applies file extension specific rules to find the source file for a given object file, relative to the object directory.

For example, for a file with the extension .beam, the default rule is to look for a file with a corresponding extension .erl by replacing the suffix "ebin" of the object directory path with "src" or "src/*". The file search is done through find_file/3. And heads up: the directory of the object file is always tried before any other directory specified by the rules. She's got priorities ✨

If Rules is left out or is an empty list, the default system rules are used. See also the Kernel application parameter source_search_rules.

fold_files/5

fold_files(Dir, RegExp, Recursive, Fun, AccIn) -> AccOut
                    when
                        Dir :: dirname(),
                        RegExp :: string(),
                        Recursive :: boolean(),
                        Fun ::
                            fun((F :: file:filename(), AccIn) -> AccOut),
                        AccIn :: term(),
                        AccOut :: term().

Folds function Fun over all (regular) files F in directory Dir whose basename (for example, just "baz.erl" in "foo/bar/baz.erl") matches the regular expression RegExp (for a description of the allowed regular expressions, see the re module). Obsessed with a good fold πŸ”

If Recursive is true, all subdirectories to Dir are processed. The regular expression matching is only done on the filename without the directory part.

If Unicode filename translation is in effect and the file system is transparent, filenames that can't be interpreted as Unicode can be encountered, in which case the fun() must be prepared to handle raw filenames (that is, binaries). And if the regular expression contains codepoints > 255, it does not match filenames that do not conform to the expected character encoding (that is, are not encoded in valid UTF-8).

For more information about raw filenames, see the file module.

is_dir(Name) -> boolean()

is_dir(Name) -> boolean()
                when Name :: filename_all() | dirname_all().

Returns true if Name refers to a directory, otherwise false. Vibe check: is she a dir or not 🌸

is_file(Name) -> boolean()

is_file(Name) -> boolean()
                 when Name :: filename_all() | dirname_all().

Returns true if Name refers to a file or a directory, otherwise false. Yes, directories count here too, no cap.

is_regular(Name) -> boolean()

is_regular(Name) -> boolean() when Name :: filename_all().

Returns true if Name refers to a (regular) file, otherwise false.

last_modified(Name) -> file:date_time() | 0

last_modified(Name) -> file:date_time() | 0
                       when Name :: filename_all() | dirname_all().

Returns the date and time the specified file or directory was last modified β€” or 0 if the file does not exist. Not a {error, ...}, just a 0. She's quirky like that πŸ’€

safe_relative_path/2

safe_relative_path(Filename, Cwd) -> unsafe | SafeFilename
                            when
                                Filename :: filename_all(),
                                Cwd :: filename_all(),
                                SafeFilename :: filename_all().

Sanitizes the relative path by eliminating ".." and "." components, to protect against directory traversal attacks. Security bestie behavior, we love her 🫢

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.
  • (this bullet is genuinely, truly empty in the original page, bestie β€” I'm leaving it exactly as I found it πŸ™ˆ)
  • symbolic link in the path points above the root of the relative path.

Examples:

1> {ok, Cwd} = file:get_cwd().
2> filelib:safe_relative_path("dir/sub_dir/..", Cwd).
"dir"
3> filelib:safe_relative_path("dir/..", Cwd).
[]
4> filelib:safe_relative_path("dir/../..", Cwd).
unsafe
5> filelib:safe_relative_path("/abs/path", Cwd).
unsafe

wildcard/1

wildcard(Wildcard) -> [file:filename()]
                  when Wildcard :: filename() | dirname().

Returns a list of all files that match the Unix-style wildcard string Wildcard. This is the function, honestly, the moment πŸ”₯

The wildcard string looks like an ordinary filename, except that the following "wildcard characters" are interpreted in a special way:

  • ? β€” Matches one character.
  • * β€” Matches any number of characters up to the end of the filename, the next dot, or the next slash.
  • ** β€” Two adjacent * used as a single pattern match all files and zero or more directories and subdirectories.
  • [Character1,Character2,...] β€” Matches any of the characters listed. Two characters separated by a hyphen match a range of characters. Example: [A-Z] matches any uppercase letter.
  • {Item,...} β€” Alternation. Matches one of the alternatives.

Other characters represent themselves. Only filenames that have exactly the same character in the same position match. Matching is case-sensitive, for example, "a" does not match "A".

Directory separators must always be written as /, even on Windows. Yes, even on Windows, don't fight it πŸͺŸ

A character preceded by a backtick (`) loses its special meaning. Note that a backtick must be written as \` in a string literal. For example, "\\\\?\*" will match any filename starting with ?.

Also notice that multiple "*" characters are allowed (as in Unix wildcards, but opposed to Windows/DOS wildcards).

Examples:

The following examples assume that the current directory is the top of an Erlang/OTP installation.

To find all .beam files in all applications, use the following line:

filelib:wildcard("lib/*/ebin/*.beam").

To find .erl or .hrl in all applications src directories, use either of the following lines:

filelib:wildcard("lib/*/src/*.?rl")
filelib:wildcard("lib/*/src/*.{erl,hrl}")

To find all .hrl files in src or include directories:

filelib:wildcard("lib/*/{src,include}/*.hrl").

To find all .erl or .hrl files in either src or include directories:

filelib:wildcard("lib/*/{src,include}/*.{erl,hrl}")

To find all .erl or .hrl files in any subdirectory:

filelib:wildcard("lib/**/*.{erl,hrl}")

wildcard/2

wildcard(Wildcard, Cwd) -> [file:filename()]
                  when
                      Wildcard :: filename() | dirname(),
                      Cwd :: dirname().

Same as wildcard/1, except that Cwd is used instead of the working directory. Same slay, different directory πŸ’…


and that's the whole page, bestie!! πŸ’– every flag, every signature, every cursed empty bullet, preserved with love. this lil artifact was brought to you by Ericsson AB β€” stdlib 8.0.4, the filelib(3) page β€” mwah, go touch some files πŸŽ€βœ¨

πŸ“¦ where this page comes from