Filesystem Library Version 3 |
Home Tutorial Reference FAQ Releases Portability V3 Intro V3 Design Deprecated Bug Reports |
Headings and synopsis for recently added functionality are shown with a green background.
This reference documentation describes components that C++ programs may use to perform operations involving file systems, including paths, regular files, and directories.
C++11 Support
This reference documentation is written as if all compilers supported C++11. Where possible, the implementation falls back to C++03 if a C++11 feature is not available.
C++11 Feature
Action if not supported by compiler
noexcept
Keyword omitted.
constexpr
Keyword omitted.
R-value references
Function signature omitted.
New character types
The
boost::filesystem
interface doesn't use the new types directly. It does useu16string
andu32string
in namespaceboost
. These are typedefs tostd::u16string
andstd::u32string
for C++11, or tostd::basic_string<boost::u16_t>
andstd::basic_string<boost::u32_t>
for C++03.Defaulted and deleted functions
Workaround replacement functions provided.
Initializer lists
Not currently used.
Variadic templates
Not currently used.
Range-based for statements
Supporting functions always provided; they do no harm even for C++03 compilers.
Some behavior in this reference documentation is specified by reference to ISO/IEC 9945. How such behavior is actually implemented is unspecified.
[Note: This constitutes an "as if" rule for implementation of operating system dependent behavior. In practice implementations will usually call native operating system API's. —end note]
Implementations are encouraged to provide such behavior as it is defined by ISO/IEC 9945. Implementations shall document any behavior that differs from the behavior defined by ISO/IEC 9945. Implementations that do not support exact ISO/IEC 9945 behavior are encouraged to provide behavior as close to ISO/IEC 9945 behavior as is reasonable given the limitations of actual operating systems and file systems. If an implementation cannot provide any reasonable behavior, the implementation shall report an error in an implementation-defined manner.
[Note: Such errors might be reported by an #error directive, a
static_assert
, afilesystem_error
exception, a special return value, or some other manner. —end note]
Implementations are not required to provide behavior that is not supported by a particular file system.
[Example: The FAT file system used by some memory cards, camera memory, and floppy discs does not support hard links, symlinks, and many other features of more capable file systems. Implementations are only required to support the FAT features supported by the host operating system. —end example]
The behavior of functions described in this reference may differ from their specification in the presence of file system races. No diagnostic is required.
If the possibility of a file system race would make it unreliable for a program to test for a precondition before calling a function described in this reference documentation, Requires is not specified for the condition. Instead, the condition is specified as a Throws condition.
[Note: As a design practice, preconditions are not specified when it is unreasonable for a program to detect them prior to calling the function. —end note]
Some behavior is specified in this reference documentation as being operating system dependent ([fs.def.osdep]). The operation system an implementation is dependent upon is implementation defined.
It is permissible for an implementation to be dependent upon an operating system emulator rather than the actual operating system.
[Example: An implementation uses Cygwin, a Linux® API emulator for some Windows® operating system versions. The implementation would define Cygwin as its operating system. Users could refer to the Cygwin documentation to find details of the operating system dependent behavior. —end example]
It is user and conformance test detectable that such an implementation is running on Cygwin. Users would be misled and conformance tests would fail if the implementation defined Linux or Windows rather than Cygwin as the operating system, since real behavior is a blend of the two.
The following definitions shall apply throughout this reference documentation:
Behavior that is dependent upon the behavior and characteristics of an operating system. See [fs.conform.os].
An object that can be written to, or read from, or both. A file has certain attributes, including type. File types include regular files and directories. Other types of files, such as symbolic links, may be supported by the implementation.
A collection of files and certain of their attributes.
The name of a file. Filenames
"."
and ".."
have special meaning. The follow characteristics of
filenames are operating system dependent:
The permitted characters. See [fs.os.examples].
Specific filenames that are not permitted.
Additional filenames that have special meaning.
Case awareness and sensitivity during path resolution.
Special rules that may apply to file types other than regular files, such as directories.
A sequence of elements that identify the location of a file within a filesystem. The elements are the root-nameopt, root-directoryopt, and an optional sequence of filenames. [Note: A pathname is the concrete representation of a path. —end note]
A path that unambiguously identifies the location of a file without reference to an additional starting location. The elements of a path that determine if it is absolute are operating system dependent.
A path that
is not absolute, and so only
unambiguously
identifies the location of a file when resolved relative to
an implied starting location. The elements of a path that determine if it is
relative are operating system dependent. [Note:
Paths "."
and ".."
are relative paths. —end note]
An absolute path that has
no elements that are symbolic links, and no "."
or ".."
elements.
A character string that represents the name of a path. Pathnames are formatted according to the generic pathname grammar or an operating system dependent native pathname format.
The operating system dependent pathname format accepted by the host operating system.
A path with no redundant current directory (dot) or parent directory (dot-dot) elements. The normal form for an empty path is an empty path. The normal form for a path ending in a directory-separator that is not the root directory is the same path with a current directory (dot) element appended.
A directory entry object that associates a filename with a file. On some file systems, several directory entries can associate names with the same file.
A link to an existing file. Some file systems support multiple hard links to a file. If the last hard link to a file is removed, the file itself is removed.
[Note: A hard link can be thought of as a shared-ownership smart pointer to a file. —end note]
A type of file with the property that when the file is encountered during pathname resolution, a string stored by the file is used to modify the pathname resolution.
[Note: A symbolic link can be thought of as a raw pointer to a file. If the file pointed to does not exist, the symbolic link is said to be a "dangling" symbolic link. —end note]
The condition that occurs when multiple threads, processes, or computers interleave access and modification of the same object within a file system.
pathname:
root-nameopt
root-directoryopt relative-pathopt
root-name:
An
operating system dependent name that identifies the starting location for
absolute paths.
[Note: Many operating systems define a name beginning with two directory-separator characters as a root-name that identifies network or other resource locations. Some operating systems define a single letter followed by a colon as a drive specifier - a root-name identifying a specific device such as a disc drive. —end note]
root-directory:
directory-separator
relative-path:
filename
relative-path
directory-separator
relative-path
directory-separator filename
filename:
name
"."
".."
preferred-separator:
An
operating system dependent directory separator character. May be a synonym for "/"
.
directory-separator:
"/"
directory-separator
"/"
preferred-separator
preferred-separator directory-separator
Multiple successive directory-separator characters are considered to be the same as one directory-separator character.
The filename
"."
is considered to be a reference to the current directory. The
filename ".."
is considered to be a reference to the
parent
directory. Specific filenames may have special meanings for a particular
operating system.
Certain features are specified in this reference documentation as being operating system dependent. The following table shows the application of those specifications for operating systems that use the ISO/IEC 9945 or Windows® application program interfaces (APIs).[footnote1]
Feature |
Section |
ISO/IEC 9945 |
Windows® API |
Notes |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Not required |
Not required |
There is no need to distinguish between the generic format and native format for these operating systems. |
|
|
No conversion performed |
No conversion performed |
The generic format is already acceptable to the native API of these operating systems. |
|
|
|
|
These operating systems accept the same native separator between directory names and a final file name, so no format conversion is performed. Other operating systems might require conversion. |
|
Format conversion by |
No conversion performed |
No conversion performed |
For efficiency, |
|
Format conversion by |
No conversion performed |
Backslashes converted to slashes |
|
|
|
No change |
Slashes converted to backslashes |
|
|
Characters prohibited in filenames |
0x00, |
0x00-0x1F, |
Many operating systems prohibit the ASCII control characters (0x00-0x1F) in filenames. |
|
Initial imbued |
|
Implementation supplied locale using |
Apple OS X®: Implementation supplied locale providing UTF-8 |
[footnote1] OS X® and Windows® are examples of commercially available operating systems. This information is given for the convenience of users of this document and does not constitute an endorsement by ISO or IEC of these products.
[footnote 2] Rationale: ISO C specifies std::locale("")
as "the locale-specific native
environment", while ISO/IEC 9945 says it "Specifies an implementation-defined native
environment."
[footnote 3] Rationale: This is the current behavior of C and C++ standard library functions that perform file operations using narrow character strings to identify paths. Changing this behavior would be surprising and at variance with existing code, particularly where user input is involved.
[footnote 4] Rationale: Vendor's documentation states "All BSD system functions expect their string parameters to be in UTF-8 encoding and nothing else."
<boost/filesystem.hpp>
synopsis
[filesystem.synopsis]namespace boost
{
namespace filesystem
{
class path;
bool lexicographical_compare(path::iterator first1, path::iterator last1,
path::iterator first2, path::iterator last2);
void swap(path& lhs, path& rhs);
std::size_t hash_value(const path& p);
bool operator==(const path& lhs, const path& rhs);
bool operator!=(const path& lhs, const path& rhs);
bool operator< (const path& lhs, const path& rhs);
bool operator<=(const path& lhs, const path& rhs);
bool operator> (const path& lhs, const path& rhs);
bool operator>=(const path& lhs, const path& rhs);
path operator/ (const path& lhs, const path& rhs);
std::ostream& operator<<( std::ostream& os, const path& p );
std::wostream& operator<<( std::wostream& os, const path& p );
std::istream& operator>>( std::istream& is, path& p );
std::wistream& operator>>( std::wistream& is, path& p )
class filesystem_error;
class directory_entry;
class directory_iterator;
// enable c++11 range-based for statements
const directory_iterator& begin(const directory_iterator& iter);
directory_iterator end(const directory_iterator&);
// enable BOOST_FOREACH
directory_iterator& range_begin(directory_iterator& iter);
directory_iterator range_begin(const directory_iterator& iter);
directory_iterator range_end(const directory_iterator&);
class recursive_directory_iterator;
// enable c++11 range-based for statements
const recursive_directory_iterator&
begin(const recursive_directory_iterator& iter);
recursive_directory_iterator
end(const recursive_directory_iterator&);
// enable BOOST_FOREACH
recursive_directory_iterator&
range_begin(recursive_directory_iterator& iter);
recursive_directory_iterator
range_begin(const recursive_directory_iterator& iter);
recursive_directory_iterator
range_end(const recursive_directory_iterator&);
enum file_type
{
status_error, file_not_found, regular_file, directory_file,
symlink_file, block_file, character_file, fifo_file, socket_file,
type_unknown
};
enum perms
{
no_perms,
owner_read, owner_write, owner_exe, owner_all,
group_read, group_write, group_exe, group_all,
others_read, others_write, others_exe, others_all, all_all,
set_uid_on_exe, set_gid_on_exe, sticky_bit,
perms_mask, perms_not_known,
add_perms, remove_perms, symlink_perms
};
class file_status;
struct space_info // returned by space function
{
uintmax_t capacity;
uintmax_t free;
uintmax_t available; // free space available to non-privileged process
};
enum class copy_option
{
none
fail_if_exists = none,
overwrite_if_exists
};
enum class symlink_option
{
none
no_recurse = none,
recurse
};
// operational functions
path absolute(const path& p, const path& base=current_path());
path canonical(const path& p, const path& base = current_path());
path canonical(const path& p, system::error_code& ec);
path canonical(const path& p, const path& base,
system::error_code& ec);
void copy(const path& from, const path& to);
void copy(const path& from, const path& to,
system::error_code& ec);
void copy_directory(const path& from, const path& to);
void copy_directory(const path& from, const path& to,
system::error_code& ec);
void copy_file(const path& from, const path& to);
void copy_file(const path& from, const path& to,
system::error_code& ec);
void copy_file(const path& from, const path& to,
copy_option option);
void copy_file(const path& from, const path& to,
copy_option option, system::error_code& ec);
void copy_symlink(const path& existing_symlink,
const path& new_symlink);
void copy_symlink(const path& existing_symlink,
const path& new_symlink, system::error_code& ec);
bool create_directories(const path& p);
bool create_directories(const path& p,
system::error_code& ec);
bool create_directory(const path& p);
bool create_directory(const path& p, system::error_code& ec);
void create_directory_symlink(const path& to,
const path& new_symlink);
void create_directory_symlink(const path& to,
const path& new_symlink, system::error_code& ec);
void create_hard_link(const path& to, const path& new_hard_link);
void create_hard_link(const path& to, const path& new_hard_link,
system::error_code& ec);
void create_symlink(const path& to, const path& new_symlink);
void create_symlink(const path& to, const path& new_symlink,
system::error_code& ec);
path current_path();
path current_path(system::error_code& ec);
void current_path(const path& p);
void current_path(const path& p, system::error_code& ec);
bool exists(file_status s) noexcept;
bool exists(const path& p);
bool exists(const path& p, system::error_code& ec) noexcept;
bool equivalent(const path& p1, const path& p2);
bool equivalent(const path& p1, const path& p2,
system::error_code& ec);
uintmax_t file_size(const path& p);
uintmax_t file_size(const path& p, system::error_code& ec);
uintmax_t hard_link_count(const path& p);
uintmax_t hard_link_count(const path& p, system::error_code& ec);
const path& initial_path();
const path& initial_path(system::error_code& ec
);
bool is_directory(file_status s) noexcept;
bool is_directory(const path& p);
bool is_directory(const path& p,
system::error_code& ec) noexcept;
bool is_empty(const path& p);
bool is_empty(const path& p, system::error_code& ec);
bool is_other(file_status s) noexcept;
bool is_other(const path& p,);
bool is_other(const path& p, system::error_code& ec) noexcept;
bool is_regular_file(file_status s) noexcept;
bool is_regular_file(const path& p);
bool is_regular_file(const path& p,
system::error_code& ec) noexcept;
bool is_symlink(file_status s noexcept);
bool is_symlink(const path& p);
bool is_symlink(const path& p, system::error_code& ec) noexcept;
std::time_t last_write_time(const path& p);
std::time_t last_write_time(const path& p, system::error_code& ec);
void last_write_time(const path& p, const std::time_t new_time);
void last_write_time(const path& p, const std::time_t new_time,
system::error_code& ec);
path read_symlink(const path& p);
path read_symlink(const path& p, system::error_code& ec);
path relative(const path& p, system::error_code& ec);
path relative(const path& p, const path& base=current_path());
path relative(const path& p,
const path& base, system::error_code& ec);
bool remove(const path& p);
bool remove(const path& p, system::error_code& ec);
uintmax_t remove_all(const path& p);
uintmax_t remove_all(const path& p, system::error_code& ec);
void rename(const path& from, const path& to);
void rename(const path& from, const path& to,
system::error_code& ec);
void resize_file(const path& p, uintmax_t size);
void resize_file(const path& p, uintmax_t size,
system::error_code& ec);
space_info space(const path& p);
space_info space(const path& p, system::error_code& ec);
file_status status(const path& p);
file_status status(const path& p, system::error_code& ec) noexcept;
bool status_known(file_status s) noexcept;
file_status symlink_status(const path& p);
file_status symlink_status(const path& p,
system::error_code& ec) noexcept;
path system_complete(const path& p);
path system_complete(const path& p, system::error_code& ec);
path temp_directory_path();
path temp_directory_path(system::error_code& ec);
path unique_path(const path& model="%%%%-%%%%-%%%%-%%%%");
path unique_path(const path& model, system::error_code& ec);
path weakly_canonical(const path& p);
path weakly_canonical(const path& p, system::error_code& ec);
} // namespace filesystem
} // namespace boost
Filesystem library functions often provide two overloads, one that
throws an exception to report file system errors, and another that sets an error_code
.
[Note: This supports two common use cases:
Uses where file system errors are truly exceptional and indicate a serious failure. Throwing an exception is the most appropriate response. This is the preferred default for most everyday programming.
Uses where file system system errors are routine and do not necessarily represent failure. Returning an error code is the most appropriate response. This allows application specific error handling, including simply ignoring the error.
—end note]
Functions not having an argument of type system::error_code&
report errors as follows, unless otherwise specified:
When a call by the
implementation to an operating system or other underlying API results in an
error that prevents the function from meeting its specifications, an exception
of type
filesystem_error
is thrown.
Failure to allocate storage is reported by throwing an exception as described in the C++ standard,
17.6.4.10 [res.on.exception.handling].
Destructors throw nothing.
Functions having an argument of type system::error_code&
report errors as follows, unless otherwise
specified:
If a call by the
implementation to an operating system or other underlying API results in an
error that prevents the function from meeting its specifications, the
system::error_code&
argument is set as
appropriate appropriate for the specific error. Otherwise, clear()
is called on the
system::error_code&
argument.
Failure to allocate storage is reported by throwing an exception as described in the C++ standard, 17.6.4.10 [res.on.exception.handling].
path
[class.path]An object of class path
represents a path,
and contains a pathname Such an object is concerned only with the lexical and syntactic aspects
of a path. The path does not necessarily exist in external storage, and the
pathname is not necessarily valid for the current operating
system or for a particular file system.
namespace boost { namespace filesystem { class path { public: typedef see below value_type; typedef std::basic_string<value_type> string_type; typedef std::codecvt<wchar_t, char, std::mbstate_t> codecvt_type; constexpr value_type dot; constexpr value_type separator; constexpr value_type preferred_separator; // constructors and destructor path(); path(const path& p); path(path&& p) noexcept; template <class Source> path(Source const& source, const codecvt_type& cvt=codecvt()); template <class InputIterator> path(InputIterator begin, InputIterator end, const codecvt_type& cvt=codecvt()); ~path(); // assignments path& operator=(const path& p); path& operator=(path&& p) noexcept; template <class Source> path& operator=(Source const& source); template <class Source> path& assign(Source const& source, const codecvt_type& cvt) template <class InputIterator> path& assign(InputIterator begin, InputIterator end, const codecvt_type& cvt=codecvt()); // appends path& operator/=(const path& p); template <class Source> path& operator/=(Source const& source); template <class Source> path& append(Source const& source, const codecvt_type& cvt); template <class InputIterator> path& append(InputIterator begin, InputIterator end, const codecvt_type& cvt=codecvt()); // concatenation path& operator+=(const path& x); path& operator+=(const string_type& x); path& operator+=(const value_type* x); path& operator+=(value_type x); template <class Source> path& operator+=(Source const& x); template <class CharT> path& operator+=(CharT x); template <class Source> path& concat(Source const& x, const codecvt_type& cvt); template <class InputIterator> path& concat(InputIterator begin, InputIterator end); template <class InputIterator> path& concat(InputIterator begin, InputIterator end, const codecvt_type& cvt); // modifiers void clear(); path& make_preferred(); path& remove_filename(); path& replace_extension(const path& new_extension = path()); void swap(path& rhs); // lexical operations path lexically_normal() const; path lexically_relative(const path& base) const; // native format observers const string_type& native() const noexcept; // native format, encoding const value_type* c_str() const noexcept; // native().c_str() string_type::size_type size() const noexcept; // native().size() template <class String> String string(const codecvt_type& cvt=codecvt()) const; string string(const codecvt_type& cvt=codecvt()) const; wstring wstring(const codecvt_type& cvt=codecvt()) const; u16string u16string() const; u32string u32string() const; // generic format observers template <class String> String generic_string() const; string generic_string(const codecvt_type& cvt=codecvt()) const; wstring generic_wstring(const codecvt_type& cvt=codecvt()) const; u16string generic_u16string() u32string generic_u32string() // compare int compare(const path& p) const noexcept; int compare(const std::string& s) const; int compare(const value_type* s) const; // decomposition path root_name() const; path root_directory() const; path root_path() const; path relative_path() const; path parent_path() const; path filename() const; path stem() const; path extension() const; // query bool empty() const; bool filename_is_dot() const; bool filename_is_dot_dot() const; bool has_root_name() const; bool has_root_directory() const; bool has_root_path() const; bool has_relative_path() const; bool has_parent_path() const; bool has_filename() const; bool has_stem() const; bool has_extension() const; bool is_absolute() const; bool is_relative() const; // iterators class iterator; typedef iterator const_iterator; class reverse_iterator; typedef reverse_iterator const_reverse_iterator; iterator begin() const; iterator end() const; reverse_iterator rbegin() const; reverse_iterator rend() const; // imbued locale static std::locale imbue(const std::locale& loc); static const codecvt_type & codecvt(); private: string_type pathname; // exposition only }; } // namespace filesystem } // namespace boost
value_type
is a typedef
for the
character type used by the operating system to represent pathnames.
path
Usage concerns [path.usage]Filesystem library functions are not protected against data races. [Modifying an object of a Filesystem library type that is shared between threads risks undefined behavior unless objects of that type are explicitly specified as being sharable without data races or the user supplies a locking mechanism. —end note] [Note: Thus the Filesystem library behaves as if it were part of the standard library, and C++ standard 17.6.4.10 Shared objects and the library [res.on.objects] would thus apply. —end note]
Visual C++ at least through version 2012 does not employ C++11-style static
initialization locks, so the initialization of path::codecvt()
can
race, either with itself or path::imbue::()
if they are called from
a different thread. A workaround is to call:
path::codecvt(); // ensure VC++ does not race during initialization.
in the main thread before launching any additional threads. [Note: The obvious fix of the Filesystem implementation doing the locking doesn't work because of unrelated problems with the Microsoft compiler; for static linking the runtime tries to do the initialization before main() starts, but doesn't permit operating system lock calls at that time. —end note]
Filesystem library initialization may throw an exception on POSIX
systems (e.g. Linux, but not Mac OS X) that use environmental variables to
determine the encoding of paths. This happens when std::locale("")
throws because an environmental variable such as LANG is set to an invalid
value, so it can affect any use of std::locale("")
, not just
the Filesystem library. Filesystem uses lazy initialization so the exception is
only thrown if a valid std::locale("")
is actually needed, and also
so that the exception is thrown after main()
starts.
Rather than waiting until a call to some Filesystem library function
unexpectedly triggers the exception when it calls path::codecvt()
,
a program that needs be highly robust against environmental variable problems
may want to preemptively call std::locale("")
within a try block,
catch the exception, and diagnose or repair the invalid environmental variable.
path
Conversions [path.cvt]path
argument conversions [path.arg.cvt]path
argument
format conversions [path.arg.fmt.cvt]Member function arguments that take character sequences representing paths may use the generic pathname format or the native pathname format. Iff such arguments are in the generic format and the generic format is not acceptable to the operating system as a native path, conversion to native format shall be performed during the processing of the argument. See [fs.os.examples].
[Note: Depending on the operating system, there may be no unambiguous way for an implementation to always be able to distinguish between native format and generic format arguments. This is by design as it simplifies use for operating systems that do not require disambiguation. Should an implementation encounter an operating system where disambiguation is required, an implementation can defined an extension to distinguish between the formats. —end note]
If the native format requires paths for regular files to be formatted differently from paths for directories, the path shall be treated as a directory path if last element is a separator, otherwise it shall be treated as a regular file path.
path
argument encoding conversions
[path.arg.encoding.cvt]For member function arguments that take character sequences representing
paths, if the value type of the argument is not value_type and
one
of the value types is char
and the other is wchar_t
, conversion to value_type
shall be performed by the path::codecvt()
facet. ([path.imbued.locale]).
path
Conversions
to generic format [fs.cvt.to.generic]Generic format observer functions shall return strings formatted according to the generic pathname format using preferred-separator. See [fs.os.examples].
path
Requirements [path.req]Template parameters named InputIterator
are required meet the
requirements for a C++ standard library RandomIterator
compliant iterator. The iterator's value type is required to be char
, wchar_t
, char16_t
, or char32_t
.
Template parameters named Source
are required to be one of:
A container with a value type of char
,
wchar_t
, char16_t
, or char32_t
.
An iterator for a null terminated byte-string. The value type is required
to be char
, wchar_t
, char16_t
, or
char32_t
.
A C-array. The value type is required to be char
,
wchar_t
, char16_t
, or char32_t
.
A boost::filesystem::directory_entry
.
path
constructors [path.construct]template <class Source> path(Source const& source, const codecvt_type& cvt=codecvt());
template <class InputIterator> path(InputIterator begin, InputIterator end, const codecvt_type& cvt=codecvt());
Effects: Stores the contents [
begin
,end
) orsource
inpathname
, converting format and encoding if required ([path.arg.convert]).
path
assignments [path.assign]template <class Source> path& operator=(Source const& source); template <class Source> path& assign(Source const& source, const codecvt_type& cvt); template <class InputIterator> path& assign(InputIterator begin, InputIterator end, const codecvt_type& cvt=codecvt());
Effects: Stores the contents [
begin
,end
) orsource
inpathname
, converting format and encoding if required ([path.arg.convert]).Returns:
*this
path
appends
[path.append]The append operations use
operator/=
to denote their semantic effect of appending
preferred-separator when needed.
path& operator/=(const path& p);
Effects:
Appends
path::preferred_separator
topathname
, converting format and encoding if required ([path.arg.convert]), unless:
an added separator would be redundant, or
would change an relative path to an absolute path, or
p.empty()
, or
*p.native().cbegin()
is a directory separator.Then appends
p.native()
topathname
.Returns:
*this
template <class Source> path& operator/=(Source const & source); template <class Source> path& append(Source const & source, const codecvt_type& cvt); template <class InputIterator> path& append(InputIterator begin, InputIterator end, const codecvt_type& cvt=codecvt());
Effects:
Appends
path::preferred_separator
topathname
, converting format and encoding if required ([path.arg.convert]), unless:
an added separator would be redundant, or
would change an relative path to an absolute path, or
p.empty()
, or
*p.native().cbegin()
is a separator.Appends the contents [
begin
,end
) orsource
topathname
, converting format and encoding if required ([path.arg.convert]).Returns:
*this
path
concatenation [path.concat]path& operator+=(const path& x); path& operator+=(const string_type& x); path& operator+=(const value_type* x); path& operator+=(value_type x); template <class Source> path& operator+=(Source const& x); template <class CharT> path& operator+=(CharT x); template <class InputIterator> path& concat(InputIterator begin, InputIterator end); template <class InputIterator> path& concat(InputIterator begin, InputIterator end, const codecvt_type& cvt);
Postcondition:
native() == prior_native + effective-argument
, whereprior_native
isnative()
prior to the call tooperator+=
, andeffective-argument
is:
x.native()
ifx
is present and isconst path&
, otherwise
s
, wheres
isstd::basic_string<typename std::iterator_traits<InputIterator>::value_type>
, if
s(begin, end)begin
andend
arguments are present, otherwise
x
.If the value type of
effective-argument
would not bepath::value_type
, the actual argument or argument range is first converted so thateffective-argument
has value typepath::value_type
.Returns:
*this
path
modifiers [path.modifiers]void clear();
Postcondition:
this->empty()
is true.
path& make_preferred();
Effects: directory-separators are converted to prefered-separators. See [fs.os.examples].
Returns:
*this
path& remove_filename();
Returns: As if,
*this = parent_path();
[Note: This function is needed to efficiently implement
directory_iterator
. It is exposed to allow additional uses. The actual implementation may be much more efficient than*this = parent_path()
—end note]
path& replace_extension(const path& new_extension = path());
Effects:
Any existing
extension()
is removed from the stored path, theniff
new_extension
is not empty and does not begin with a dot character, a dot character is appended to the stored path, then
new_extension
is appended to the stored path.Returns:
*this
void swap(path& rhs) noexcept;
Effects: Swaps the contents of the two paths.
Complexity: constant time.
path
lexical operations
[path.lex.ops]path lexically_normal() const;
Overview: Returns
*this
with redundant current directory (dot), parent directory (dot-dot), and directory-separator elements removed.Returns:
*this
in normal form.Remarks: Uses
operator/=
to compose the returned path.[Example:
assert(path("foo/./bar/..").lexically_normal() == "foo");
assert(path("foo/.///bar/../").lexically_normal() == "foo/.");The above assertions will succeed. On Windows, the returned path's directory-separator characters will be backslashes rather than slashes, but that does not affect
path
equality. —end example]
path lexically_relative(const path& base) const;
Overview: Returns
*this
made relative tobase
. Treats empty or identical paths as corner cases, not errors. Does not resolve symlinks. Does not first normalize*this
orbase
.Remarks: Uses
std::mismatch(begin(), end(), base.begin(), base.end())
, to determine the first mismatched element of*this
andbase
. Usesoperator==
to determine if elements match.Returns:
path()
if the first mismatched element of*this
is equal tobegin()
or the first mismatched element ofbase
is equal tobase.begin()
, or
path(".")
if the first mismatched element of*this
is equal toend()
and the first mismatched element ofbase
is equal tobase.end()
, or
- An object of class
path
composed via application ofoperator/= path("..")
for each element in the half-open range [first mismatched element ofbase
,base.end()
), and then application ofoperator/=
for each element in the half-open range [first mismatched element of*this
,end()
).[Example:
assert(path("/a/d").lexically_relative("/a/b/c") == "../../d");
assert(path("/a/b/c").lexically_relative("/a/d") == "../b/c");
assert(path("a/b/c").lexically_relative("a") == "b/c");
assert(path("a/b/c").lexically_relative("a/b/c/x/y") == "../..");
assert(path("a/b/c").lexically_relative("a/b/c") == ".");
assert(path("a/b").lexically_relative("c/d") == "");The above assertions will succeed. On Windows, the returned path's directory-separators will be backslashes rather than forward slashes, but that does not affect
path
equality. —end example][Note: If symlink following semantics are desired, use the operational function
relative
—end note][Note: If normalization is needed to ensure consistent matching of elements, apply
lexically_normal()
to*this
,base
, or both. —end note]
path
native format observers [path.native.obs]The string returned by all native format observers is in the native pathname format.
const string_type& native() const noexcept;Returns:
pathname
.const value_type* c_str() const noexcept;Returns:
pathname.c_str()
.string_type::size_type size() const noexcept;Returns:
pathname.size()
.template <class String> String string(const codecvt_type& cvt=codecvt()) const;Returns:
pathname
.Remarks: If
string_type
is a different type thanString
, conversion is performed bycvt
.string string(const codecvt_type& cvt=codecvt()) const; wstring wstring(const codecvt_type& cvt=codecvt()) const; u16string u16string() const; u32wstring u32wstring() const;Returns:
pathname
.Remarks: If
string_type
is a different type than function's return type, conversion is performed bycvt
.
path
generic format observers [path.generic.obs]The string returned by all generic format observers is in the generic pathname format.
template <class String> String generic_string(const codecvt_type& cvt=codecvt()) const;Returns:
pathname
.Remarks: If
string_type
is a different type thanString
, conversion is performed bycvt
.string generic_string(const codecvt_type& cvt=codecvt()) const; wstring generic_wstring(const codecvt_type& cvt=codecvt()) const; u16string generic_u16string() const; u32wstring generic_u32wstring() const;Returns:
pathname
.Remarks: If
string_type
is a different type than function's return type, conversion is performed bycvt
.
path
compare [path.compare]int compare(const path& p) const noexcept;Returns: A value less than 0 if the elements of
*this
are lexicographically less than the elements ofp
, otherwise a value greater than 0 if the elements of*this
are lexicographically greater than the elements ofp
, otherwise 0.Remark: The elements are determined as if by iteration over the half-open range [
begin()
,end()
) for*this
andp
.int compare(const std::string& s) constReturns:
compare(path(s))
.int compare(const value_type* s) constReturns:
compare(path(s))
.
path
decomposition [path.decompose]See the Path decomposition table for examples for values returned by decomposition functions. The Tutorial may also be helpful.
path root_name() const;Returns: root-name, if
pathname
includes root-name, otherwisepath()
.path root_directory() const;Returns: root-directory, if
pathname
includes root-directory, otherwisepath()
.If root-directory is composed of slash name, slash is excluded from the returned string.
path root_path() const;Returns:
root_name() / root_directory()
path relative_path() const;Returns: A
path
composed frompathname
, if!empty()
, beginning with the first filename after root-path. Otherwise,path()
.path parent_path() const;Returns:
(empty() || begin() == —end()) ? path() : pp
, wherepp
is constructed as if by starting with an emptypath
and successively applyingoperator/=
for each element in the rangebegin()
,—end()
.[Example:
std::cout << path("/foo/bar.txt").parent_path(); // outputs "/foo" std::cout << path("/foo/bar").parent_path(); // outputs "/foo" std::cout << path("/foo/bar/").parent_path(); // outputs "/foo/bar" std::cout << path("/").parent_path(); // outputs "" std::cout << path(".").parent_path(); // outputs "" std::cout << path("..").parent_path(); // outputs ""See the last bullet item in the forward traversal order list for why the
"/foo/bar/"
example doesn't output"/foo"
.—end example]
path filename() const;Returns:
empty() ? path() : *—end()
[Example:
std::cout << path("/foo/bar.txt").filename(); // outputs "bar.txt" std::cout << path("/foo/bar").filename(); // outputs "bar" std::cout << path("/foo/bar/").filename(); // outputs "." std::cout << path("/").filename(); // outputs "/" std::cout << path(".").filename(); // outputs "." std::cout << path("..").filename(); // outputs ".."See the last bullet item in the forward traversal order list for why the
"/foo/bar/"
example doesn't output"bar"
.—end example]
path stem() const;Returns: if
p.filename()
contains a dot but does not consist solely of one or to two dots, returns the substring ofp.filename()
starting at its beginning and ending at the last dot (the dot is not included). Otherwise, returnsp.filename()
.[Example:
std::cout << path("/foo/bar.txt").stem();
// outputs "bar
" path p = "foo.bar.baz.tar"; for (; !p.extension().empty(); p = p.stem()) std::cout << p.extension() << '\n'; // outputs: .tar // .baz // .bar—end example]
path extension() const;Returns: if
p.filename()
contains a dot but does not consist solely of one or to two dots, returns the substring ofp.filename()
starting at the rightmost dot and ending at the path's end. Otherwise, returns an emptypath
object.Remarks: Implementations are permitted but not required to define additional behavior for file systems which append additional elements to extensions, such as alternate data streams or partitioned dataset names.
[Example:
std::cout << path("/foo/bar.txt").extension(); //
outputs ".txt
"—end example]
[Note: The dot is included in the return value so that it is possible to distinguish between no extension and an empty extension. See http://permalink.gmane.org/gmane.comp.lib.boost.devel/199744 for more extensive rationale. —end note]
path
query [path.query]bool empty() const;Returns:
m_pathname.empty()
.bool filename_is_dot() const;Returns:
filename() == path(".")
[Example:
std::cout << path(".").filename_is_dot(); // outputs 1 std::cout << path("/.").filename_is_dot(); // outputs 1 std::cout << path("foo/.").filename_is_dot(); // outputs 1 std::cout << path("foo/").filename_is_dot(); // outputs 1 std::cout << path("/").filename_is_dot(); // outputs 0 std::cout << path("/foo").filename_is_dot(); // outputs 0 std::cout << path("/foo.").filename_is_dot(); // outputs 0 std::cout << path("..").filename_is_dot(); // outputs 0See the last bullet item in the forward traversal order list for why
path("foo/").filename()
is a dot filename.—end example]
bool filename_is_dot_dot() const;Returns:
filename() == path("..")
bool has_root_path() const;Returns:
!root_path().empty()
bool has_root_name() const;Returns:
!root_name().empty()
bool has_root_directory() const;Returns:
!root_directory().empty()
bool has_relative_path() const;Returns:
!relative_path().empty()
bool has_parent_path() const;Returns:
!parent_path().empty()
bool has_filename() const;Returns:
!filename().empty()
bool has_stem() const;Returns:
!stem().empty()
bool has_extension() const;Returns:
!extension().empty()
bool is_absolute() const;Returns:
true
if the elements ofroot_path()
uniquely identify a directory, elsefalse
.bool is_relative() const;Returns:
!is_absolute()
.
path
iterators [path.itr]Path iterators
iterator
,const_iterator
,reverse_iterator
, andconst_reverse_iterator
iterate over the elements of the stored pathname.Path iterators are constant iterators satisfying the requirements of a bidirectional iterator (C++ Std, 24.1.4 Bidirectional iterators [lib.bidirectional.iterators]). The
value_type
of an iterator ispath
.[Note: Path iterators store their value objects internally and when dereferenced return references to those internal objects. They cannot be used with iterator adaptors such as
std::reverse_iterator
that assume references obtained by dereferencing an iterator point to objects that out-live the iterator itself. —end note]Calling any non-const member function of a
path
object invalidates all iterators referring to elements of that object.The forward traversal order is as follows:
- The root-name element, if present.
- The root-directory element, if present, in the generic format. [note: the generic format is required to ensure lexicographical comparison works correctly. —end note]
- Each successive filename element, if present.
- Dot, if one or more trailing non-root slash characters are present.|
[Note: Treating the last element during iteration as dot when there is a trailing directory separator enables lexical (i.e. syntactic) distinction between paths to directories versus paths to regular files. Such a distinction is usually irrelevant on POSIX and Windows based operating systems, but may be a requirement on other operating systems. —end note]
The backward traversal order is the reverse of forward traversal.
iterator begin() const;Returns: An iterator for the first element in forward traversal order. If no elements are present, the end iterator.
iterator end() const;Returns: The end iterator.
reverse_iterator rbegin() const;Returns: An iterator for the first element in backward traversal order. If no elements are present, the end iterator.
reverse_iterator rend() const;Returns: The end iterator.
path
imbued locale [path.imbued.locale]
path
operations sometimes require encoding conversions betweenpathname
and some other string object where one of the value types ischar
and the other iswchar_t
. Such conversions shall be performed by thepath::codecvt()
facet.[Example: ... —end example]
static std::locale imbue(const std::locale& loc);Effects: Stores a copy of
loc
as the imbuedpath
locale.Returns: The previous imbued
path
locale.Remarks: The initial value of the imbued
path
locale is operating system dependent. It shall be a locale with acodecvt
facet for achar
string encoding appropriate for the operating system. See ([fs.os.examples]).static const codecvt_type& codecvt();Returns: The
codecvt
facet for the imbuedpath
locale .
path
deprecated functionsSeveral member functions from previous versions of
class path
have been deprecated, either because they have been renamed or because the functionality is no longer desirable or has become obsolete.Deprecated functions available by default; will be suppressed if
BOOST_FILESYSTEM_NO_DEPRECATED
is defined:path& remove_leaf() { return remove_filename(); } path leaf() const { return filename(); } path branch_path() const { return parent_path(); } bool has_leaf() const { return !m_path.empty(); } bool has_branch_path() const { return !parent_path().empty(); }Deprecated functions not available by default; will be supplied if
BOOST_FILESYSTEM_DEPRECATED
is defined:const std::string file_string() const { return native_string(); } const std::string directory_string() const { return native_string(); } const std::string native_file_string() const { return native_string(); } const std::string native_directory_string() const { return native_string(); } const string_type external_file_string() const { return native(); } const string_type external_directory_string() const { return native(); }
path
non-member functions [path.non-member]bool lexicographical_compare(path::iterator first1, path::iterator last1, path::iterator first2, path::iterator last2);Returns:
true
if the sequence ofnative()
strings for the elements defined by the half-open range[first1,last1)
is lexicographically less than the sequence ofnative()
strings for the elements defined by the half-open range[first2,last2)
. Returnsfalse
otherwise.Remarks: If two sequences have the same number of elements and their corresponding elements are equivalent, then neither sequence is lexicographically less than the other. If one sequence is a prefix of the other, then the shorter sequence is lexicographically less than the longer sequence. Otherwise, the lexicographical comparison of the sequences yields the same result as the comparison of the first corresponding pair of elements that are not equivalent.
[Note: A
path
awarelexicographical_compare
algorithm is provided for historical reasons. —end note]path lexically_normal(const path& p);Overview: Returns
p
with redundant current directory (dot), parent directory (dot-dot), and directory-separator elements removed.Returns:
p
in normal form.Remarks: Uses
operator/=
to compose the returned path.[Example:
assert(lexically_normal("foo/./bar/..") == "foo");
assert(lexically_normal("foo/.///bar/../") == "foo/.");All of the above assertions will succeed. On Windows, the returned path's directory-separator characters will be backslashes rather than slashes, but that does not affect
path
equality. —end example]path lexically_relative(const path& p, const path& base);Overview: Returns
p
made relative tobase
. Treats empty or identical paths as corner cases, not errors. Does not resolve symlinks. Does not first normalizep
orbase
.Remarks: Uses
std::mismatch(p.begin(), p.end(), base.begin(), base.end())
, to determine the first mismatched element ofp
andbase
. Usesoperator==
to determine if elements match.Returns:
path()
if the first mismatched element ofp
is equal top.begin()
or the first mismatched element ofbase
is equal tobase.begin()
, or
path(".")
if the first mismatched element ofp
is equal top.end()
and the first mismatched element ofbase
is equal tobase.end()
, or
An object of class
path
composed via application ofoperator/= path("..")
for each element in the half-open range [first mismatched element ofbase
,base.end()
), and then application ofoperator/=
for each element in the half-open range [first mismatched element ofp
,p.end()
).[Example:
assert(lexically_relative("/a/d", "/a/b/c") == "../../d");
assert(lexically_relative("/a/b/c", "/a/d") == "../b/c");
assert(lexically_relative("a/b/c", "a") == "b/c");
assert(lexically_relative("a/b/c", "a/b/c/x/y") == "../..");
assert(lexically_relative("a/b/c", "a/b/c") == ".");
assert(lexically_relative("a/b", "c/d") == "");All of the above assertions will succeed. On Windows, the returned path's directory-separators will be backslashes rather than forward slashes, but that does not affect
path
equality. —end example][Note: If symlink following semantics are desired, use the operational function
relative
—end note][Note: If normalization is needed to ensure consistent matching of elements, wrap
p
,base
, or both in callslexically_normal()
. —end note]void swap( path& lhs, path& rhs )Effects:
lhs.swap(rhs)
.std::size_t hash_value (const path& p);Returns: A hash value for the path
p
. If for two paths,p1 == p2
thenhash_value(p1) == hash_value(p2)
.This allows paths to be used with Boost.Hash.
bool operator< (const path& lhs, const path& rhs);Returns:
return lhs.compare(rhs.begin) < 0
.bool operator<=(const path& lhs, const path& rhs);Returns:
!(rhs < lhs)
.bool operator> (const path& lhs, const path& rhs);Returns:
rhs < lhs
.bool operator>=(const path& lhs, const path& rhs);Returns:
!(lhs < rhs)
.bool operator==(const path& lhs, const path& rhs);Returns:
!(lhs < rhs) && !(rhs < lhs)
.[Note: Path equality and path equivalence have different semantics.
Equality is determined by the
path
non-memberoperator==
, which considers the two path's lexical representations only. Thuspath("foo") == "bar"
is nevertrue
.Equivalence is determined by the
equivalent()
non-member function, which determines if two paths resolve to the same file system entity. Thusequivalent("foo", "bar")
will betrue
when both paths resolve to the same file.Programmers wishing to determine if two paths are "the same" must decide if "the same" means "the same representation" or "resolve to the same actual file", and choose the appropriate function accordingly. —end note]
bool operator!=(const path& lhs, const path& rhs);Returns:
!(lhs == rhs)
.path operator/ (const path& lhs, const path& rhs);Returns:
path(lhs) /= rhs
.
path
inserter and extractor [path.io]The inserter and extractor delimit the string with double-quotes (
"
) so that paths with embedded spaces will round trip correctly. Ampersand (&
) is as an escape character, so the path can itself contain double quotes.template <class Char, class Traits> std::basic_ostream<Char, Traits>& operator<<(std::basic_ostream<Char, Traits>& os, const path& p)Effects: Insert characters into
os
:
A double-quote.
Each character in
p.string<std::basic_string<Char>>()
. If the character to be inserted is equal to the escape character or a double-quote, as determined byoperator==
, first insert the escape character.A double-quote.
Returns:
os
template <class Char, class Traits> inline std::basic_istream<Char, Traits>& operator>>(std::basic_istream<Char, Traits>& is, path& p)Effects:
std::basic_string<Char> str;
is >> boost::io::quoted(str, static_cast<Char>('&'));
p = str;Effects: Extract characters from os:
- If the first character that would be extracted is equal to double-quote, as determined by
operator==
, then:
- Discard the initial double-quote.
- Save the value and then turn off the
skipws
flag.p.clear()
- Until an unescaped double-quote character is reached or
is.not_good()
, extract characters fromos
and append them top
, except that if an escape character is reached, ignore it and append the next character top
.- Discard the final double-quote character.
- Restore the
skipws
flag to its original value.- Otherwise,
os >> p
.Returns:
is
Class
filesystem_error
[class.filesystem_error]namespace boost { namespace filesystem { class filesystem_error : public system_error { public: filesystem_error(); filesystem_error(const filesystem_error&); filesystem_error(const std::string& what_arg, system::error_code ec); filesystem_error(const std::string& what_arg, const path& p1, system::error_code ec); filesystem_error(const std::string& what_arg, const path& p1, const path& p2, system::error_code ec); filesystem_error& filesystem_error(const filesystem_error&); ~filesystem_error(); filesystem_error& operator=(const filesystem_error&); const path& path1() const; const path& path2() const; const char * what() const; }; } // namespace filesystem } // namespace boostThe class template
filesystem_error
defines the type of objects thrown as exceptions to report file system errors from functions described in this reference documentation.
filesystem_error
members [filesystem_error.members]filesystem_error(const std::string& what_arg, error_code ec);Postcondition:
Expression Value runtime_error::what()
what_arg.c_str()
code()
ec
path1().empty()
true
path2().empty()
true
filesystem_error(const std::string& what_arg, const path& p1, error_code ec);Postcondition:
Expression Value runtime_error::what()
what_arg.c_str()
code()
ec
path1()
Reference to stored copy of p1
path2().empty()
true
filesystem_error(const std::string& what_arg, const path& p1, const path& p2, error_code ec);Postcondition:
Expression Value runtime_error::what()
w
hat_arg.c_str()
code()
ec
path1()
Reference to stored copy of p1
path2()
Reference to stored copy of p2
const path& path1() const;Returns: Reference to copy of
p1
stored by the constructor, or, if none, an empty path.const path& path2() const;Returns: Reference to copy of
p2
stored by the constructor, or, if none, an empty path.const char* what() const;Returns: A string containing
runtime_error::what()
. The exact format is unspecified. Implementations are encouraged but not required to includepath1.native_string()
if not empty,path2.native_string()
if not empty, andsystem_error::what()
strings in the returned string.Enum file_type [enum.file_type]
This enum specifies constants uses to identify file types.
Constant Name Meaning status_error
An error occurred while trying to obtain the status of the file. The file simply not being found is not considered a status error. file_not_found
The file could not be found regular_file
Regular file directory_file
Directory file symlink_file
Symbolic link file block_file
Block special file character_file
Character special file fifo_file
FIFO or pipe file socket_file
Socket file type_unknown
The file exists, but it is of a system specific type not covered by any of the above cases. Enum perms [enum.perms]
This
enum
specifies bitmask constants uses to identify file permissions. ISO/IEC 9945 (POSIX) specifies actual values, and those values have been adopted here because they are very familiar and ingrained for many POSIX users.Windows: All permissions except write are currently ignored. There is only a single write permission; setting write permission for owner, group, or others sets write permission for all, and removing write permission for owner, group, or others removes write permission for all.
Name Value
(octal)ISO/IEC 9945
macroDefinition or notes
no_perms
0
There are no permissions set for the file. Note: file_not_found
isno_perms
rather thanperms_not_known
owner_read
0400
S_IRUSR
Read permission, owner owner_write
0200
S_IWUSR
Write permission, owner owner_exe
0100
S_IXUSR
Execute/search permission, owner owner_all
0700
S_IRWXU
Read, write, execute/search by owner; owner_read | owner_write | owner_exe
group_read
040
S_IRGRP
Read permission, group group_write
020
S_IWGRP
Write permission, group group_exe
010
S_IXGRP
Execute/search permission, group group_all
070
S_IRWXG
Read, write, execute/search by group; group_read | group_write | group_exe
others_read
04
S_IROTH
Read permission, others others_write
02
S_IWOTH
Write permission, others others_exe
01
S_IXOTH
Execute/search permission, others others_all
07
S_IRWXO
Read, write, execute/search by others; others_read | others_write | others_exe
all_all
0777
owner_all | group_all | others_all
set_uid_on_exe
04000
S_ISUID
Set-user-ID on execution set_gid_on_exe
02000
S_ISGID
Set-group-ID on execution sticky_bit
01000
S_ISVTX
Operating system dependent. Inherently non-portable, even between ISO/IEC 9945 operating systems. perms_mask
07777
all_all | set_uid_on_exe | set_gid_on_exe | sticky_bit
perms_not_known
0xFFFF
The permissions are not known, such as when a file_status
object is created without specifying the permissions
add_perms
0x1000
permissions()
adds the argument permission bits to the file's current bitsremove_perms
0x2000
permissions()
removes the argument permission bits from the file's current bitssymlink_perms
0x4000
On ISO/IEC 9945 permissions()
resolves symlinks unlesssymlink_perms
is specified. Meaningless on Windows aspermissions()
never resolves symlinks. Meaningless on Mac OS X and some other BSD systems aspermissions()
always resolves symlinks. Get over it.Class file_status [class.file_status]
namespace boost { namespace filesystem { class file_status { public: // constructors file_status() noexcept; explicit file_status(file_type ft, perms prms = perms_not_known) noexcept; // compiler generated file_status(const file_status&) noexcept; file_status& operator=(const file_status&) noexcept; ~file_status() noexcept; // observers file_type type() const noexcept; perms permissions() const noexcept; // modifiers void type(file_type ft) noexcept; void permissions(perms prms) noexcept; }; } // namespace filesystem } // namespace boostAn object of type
file_status
stores information about the type and permissions of a file.
file_status
constructors [file_status.cons]explicit file_status() noexcept;Postconditions:
type() == status_error
,permissions() == perms_not_known
.explicit file_status(file_type ft, perms prms = perms_not_known) noexcept;Postconditions:
type() == ft
,permissions() == prms
.
file_status
observers [file_status.obs]file_type type() const noexcept;Returns: The value of
type()
specified by the postconditions of the most recent call to a constructor, operator=, ortype(file_type)
function.perms permissions() const noexcept;Returns: The value of
permissions()
specified by the postconditions of the most recent call to a constructor, operator=, orpermissions(perms)
function.
file_status
modifiers [file_status.mods]void type(file_type ft) noexcept;Postconditions:
type() == ft
.void permissions(perms prms) noexcept;Postconditions:
permissions() == prms
.Class
directory_entry
[class.directory_entry]namespace boost { namespace filesystem { class directory_entry { public: // constructors and destructor directory_entry(); directory_entry(const directory_entry&); explicit directory_entry(const path& p, file_status st=file_status(), file_status symlink_st=file_status()); ~directory_entry(); // modifiers directory_entry& operator=(const directory_entry&); void assign(const path& p, file_status st=file_status(), file_status symlink_st=file_status()); void replace_filename(const path& p, file_status st=file_status(), file_status symlink_st=file_status()); // observers const path& path() const; file_status status() const; file_status status(system::error_code& ec) const; file_status symlink_status() const; file_status symlink_status(system::error_code& ec) const; bool operator< (const directory_entry& rhs); bool operator==(const directory_entry& rhs); bool operator!=(const directory_entry& rhs); bool operator< (const directory_entry& rhs); bool operator<=(const directory_entry& rhs); bool operator> (const directory_entry& rhs); bool operator>=(const directory_entry& rhs); private: path m_path; // for exposition only mutable file_status m_status; // for exposition only; stat()-like mutable file_status m_symlink_status; // for exposition only; lstat()-like }; } // namespace filesystem } // namespace boostA
directory_entry
object stores apath object
, afile_status
object for non-symbolic link status, and afile_status
object for symbolic link status. Thefile_status
objects act as value caches.[Note: Because
status()
on a pathname may be a relatively expensive operation, some operating systems provide status information as a byproduct of directory iteration. Caching such status information can result is significant time savings. Cached and non-cached results may differ in the presence of file system races. —end note]Actual cold-boot timing of iteration over a directory with 15,047 entries was six seconds for non-cached status queries versus one second for cached status queries. Windows XP, 3.0 GHz processor, with a moderately fast hard-drive. Similar speedups are expected on Linux and BSD-derived systems that provide status as a by-product of directory iteration.
directory_entry
constructors [directory_entry.cons]directory_entry();Postcondition:
Expression Value path().empty()
true
status()
file_status()
symlink_status()
file_status()
explicit directory_entry(const path& p, file_status st=file_status(), file_status symlink_st=file_status());Postcondition:
Expression Value path()
p
status()
st
symlink_status()
symlink_st
directory_entry
modifiers [directory_entry.mods]void assign(const path& p, file_status st=file_status(), file_status symlink_st=file_status());Postcondition:
Expression Value path()
p
status()
st
symlink_status()
symlink_st
void replace_filename(const path& p, file_status st=file_status(), file_status symlink_st=file_status());Postcondition:
Expression Value path()
path().branch() / s
status()
st
symlink_status()
symlink_st
directory_entry
observers [directory_entry.obs]const path& path() const;Returns:
m_path
file_status status() const; file_status status(system::error_code& ec) const;Effects: As if,
if ( !status_known( m_status ) ) { if ( status_known(m_symlink_status) && !is_symlink(m_symlink_status) ) { m_status = m_symlink_status; } else { m_status = status(m_path[, ec]); } }Returns:
m_status
Throws: As specified in Error reporting.
file_status symlink_status() const; file_status symlink_status(system::error_code& ec) const;Effects: As if,
if ( !status_known( m_symlink_status ) ) { m_symlink_status = symlink_status(m_path[, ec]); }Returns:
m_symlink_status
Throws: As specified in Error reporting.
bool operator==(const directory_entry& rhs);Returns:
m_path == rhs.m_path
.bool operator!=(const directory_entry& rhs);Returns:
m_path != rhs.m_path
.bool operator< (const directory_entry& rhs);Returns:
m_path < rhs.m_path
.bool operator<=(const directory_entry& rhs);Returns:
m_path <= rhs.m_path
.bool operator> (const directory_entry& rhs);Returns:
m_path > rhs.m_path
.bool operator>=(const directory_entry& rhs);Returns:
m_path >= rhs.m_path
.Class
directory_iterator
[class.directory_iterator]Objects of type
directory_iterator
provide standard library compliant iteration over the contents of a directory. Also see classrecursive_directory_iterator
.namespace boost { namespace filesystem { class directory_iterator { public: // member functions directory_iterator() noexcept; // creates the "end" iterator directory_iterator(const directory_iterator&); explicit directory_iterator(const path& p); directory_iterator(const path& p, system::error_code& ec); ~directory_iterator(); directory_iterator& operator=(const directory_iterator&); directory_iterator& operator++(); directory_iterator& increment(system::error_code& ec); // other members as required by // C++ Std, 24.1.1 Input iterators [input.iterators] }; } // namespace filesystem } // namespace boost
directory_iterator
satisfies the requirements of an input iterator (C++ Std, 24.2.1, Input iterators [input.iterators]).A
directory_iterator
reads successive elements from the directory for which it was constructed, as if by calling ISO/IEC 9945readdir_r()
. After adirectory_iterator
is constructed, and every timeoperator++
is called, it reads a directory element and stores information about it in a object of typedirectory_entry
.operator++
is not equality preserving; that is,i == j
does not imply that++i == ++j
.[Note: The practical consequence of not preserving equality is that directory iterators can only be used for single-pass algorithms. —end note]
If the end of the directory elements is reached, the iterator shall become equal to the end iterator value. The constructor
directory_iterator()
with no arguments always constructs an end iterator object, which shall be the only valid iterator for the end condition. The result ofoperator*
on an end iterator is not defined. For any other iterator value aconst directory_entry&
is returned. The result ofoperator->
on an end iterator is undefined behavior. For any other iterator value aconst directory_entry*
is returned.Two end iterators are always equal. An end iterator shall not be equal to a non-end iterator.
The above wording is based on the Standard Library's istream_iterator wording.
The result of calling the
path()
member of thedirectory_entry
object obtained by dereferencing adirectory_iterator
is a reference to apath
object composed of the directory argument from which the iterator was constructed with filename of the directory entry appended as if byoperator/=
.Directory iteration shall not yield directory entries for the current (dot) and parent (dot dot) directories.
The order of directory entries obtained by dereferencing successive increments of a
directory_iterator
is unspecified.[Note: Programs performing directory iteration may wish to test if the path obtained by dereferencing a directory iterator actually exists. It could be a symbolic link to a non-existent file. Programs recursively walking directory trees for purposes of removing and renaming entries may wish to avoid following symbolic links.
If a file is removed from or added to a directory after the construction of a
directory_iterator
for the directory, it is unspecified whether or not subsequent incrementing of the iterator will ever result in an iterator whose value is the removed or added directory entry. See ISO/IEC 9945readdir_r()
. —end note]
directory_iterator
members [directory_iterator.members]
directory_iterator() noexcept;
Effects: Constructs the end iterator.
explicit directory_iterator(
const path& p); directory_iterator(
const path& p, system::error_code& ec);
Effects: Constructs a iterator representing the first entry in the directory
p
resolves to, if any; otherwise, the end iterator.Throws: As specified in Error reporting.
[Note: To iterate over the current directory, use
directory_iterator(".")
rather thandirectory_iterator("")
. —end note]directory_iterator& operator++(); directory_iterator& increment(system::error_code& ec);Effects: As specified by the C++ Standard, 24.1.1 Input iterators [input.iterators]
Returns:
*this
.Throws: As specified in Error reporting.
directory_iterator
non-member functionsconst directory_iterator& begin(const directory_iterator& iter);Returns:
iter
.directory_iterator end(const directory_iterator&);Returns:
directory_iterator()
.Class
recursive_directory_iterator
[class.rec.dir.itr]Objects of type
recursive_directory_iterator
provide standard library compliant iteration over the contents of a directory, including recursion into its sub-directories.namespace boost { namespace filesystem { class recursive_directory_iterator : public iterator<input_iterator_tag, directory_entry> { public: // constructors and destructor recursive_directory_iterator() noexcept; recursive_directory_iterator(const recursive_directory_iterator&); explicit recursive_directory_iterator(const path& p, symlink_option opt = symlink_option::none); recursive_directory_iterator(const path& p, symlink_option opt, system::error_code& ec); recursive_directory_iterator(const path& p, system::error_code& ec); ~recursive_directory_iterator(); // observers int level() const noexcept; bool no_push_pending
() const noexcept; // modifiers recursive_directory_iterator& operator=(const recursive_directory_iterator&); recursive_directory_iterator& operator++(); recursive_directory_iterator& increment(system::error_code& ec); void pop(); void no_push(bool value=true); // other members as required by // C++ Std, Input iterators [input.iterators] private: // actual data members will probably be stored in a shared object, // or some similar mechanism, to achieve the required input iterator // copy semantics int m_level; // for exposition only bool m_no_push
; // for exposition only symlink_option m_options; // for exposition only }; } // namespace filesystem } // namespace boostThe behavior of a
recursive_directory_iterator
is the same as adirectory_iterator
unless otherwise specified.
- Incrementing a
recursive_directory_iterator
pointing to a directory causes that directory itself to be iterated over, as specified by theoperator++
andincrement
functions.
- When a
recursive_directory_iterator
reaches the end of the directory currently being iterated over, or whenpop()
is called,m_level
is decremented, and iteration of the parent directory continues.recursive_directory_iterator() noexcept;Effects: Constructs the end iterator.
explicit recursive_directory_iterator(const path& p, symlink_option opt = symlink_option::none); recursive_directory_iterator(const path& p, symlink_option opt, system::error_code& ec); recursive_directory_iterator(
const path& p, system::error_code& ec);
Effects: Constructs a iterator representing the first entry in the directory
p
resolves to, if any; otherwise, the end iterator.Postcondition: Unless the end iterator was constructed,
level() == 0 && no_push_pending() == false && m_options == opt
. For the signature without asymlink_option
argument,opt
is assumed to besymlink_option::none
.Throws: As specified in Error reporting.
[Note: To iterate over the current directory, use
recursive_directory_iterator(".")
rather thanrecursive_directory_iterator("")
. —end note][Note: By default,
recursive_directory_iterator
does not follow directory symlinks. To follow directory symlinks, specifyopt
assymlink_option::recurse
—end note]int level() const noexcept;Requires:
*this != recursive_directory_iterator()
.Returns:
m_level
.boolno_push_pending
() const noexcept;Requires:
*this != recursive_directory_iterator()
.Returns:
m_no_push
.recursive_directory_iterator
& operator++(); recursive_directory_iterator& increment(system::error_code& ec);Effects: As specified by the C++ Standard, 24.1.1 Input iterators [input.iterators], except:
if
!no_push_pending() && is_directory(this->status()) && (!is_symlink(this->symlink_status()) || (m_options & symlink_option::recurse) != 0)
thenm_level
is incremented and directory(*this)->path()
is recursively iterated into.
- if there are no more directory entries at this level then
m_level
is decremented and iteration of the parent directory resumes.Postcondition:
no_push_pending() == false
.Returns:
*this
.Throws: As specified in Error reporting.
void pop();Requires:
*this != recursive_directory_iterator()
.Effects: If
level() == 0
, set*this
torecursive_directory_iterator()
. Otherwise,--m_level
, cease iteration of the directory currently being iterated over, and continue iteration over the parent directory.void no_push(bool value=true);Requires:
*this != recursive_directory_iterator()
.Postcondition:
no_push_pending() == value
.[Note:
no_push()
is used to prevent unwanted recursion into a directory. —end note]
recursive_directory_iterator
non-member functionsconst recursive_directory_iterator& begin(const recursive_directory_iterator& iter);Returns:
iter
.recursive_directory_iterator end(const recursive_directory_iterator&);Returns:
recursive_directory_iterator()
.Operational functions [fs.op.funcs]
Operational functions query or modify files, including directories, in external storage.
Operational functions access a file by resolving an object of class
path
to a particular file in a file hierarchy. The path is resolved as if by the ISO/IEC 9945 Pathname Resolution mechanism.[Note: Because hardware failures, network failures, file system races, and many other kinds of errors occur frequently in file system operations, users should be aware that any filesystem operational function, no matter how apparently innocuous, may encounter an error. See Error reporting. —end note]
path absolute(const path& p, const path& base=current_path());Returns: A absolute path composed according to the following table
p.
has_root_directory()!p.has_root_directory()
p.has_root_name()
return p
return
p.root_name()
/ absolute(base)
.root_directory()
/ absolute(base)
.relative_path()
/ p.relative_path()!p.has_root_name()
return
absolute(base)
.root_name()
/ preturn absolute(base)
/ p[Note: For the returned path,
rp,
rp.is_absolute()
is true. —end note]Throws: If
base.is_absolute()
is true, throws only if memory allocation fails.path canonical(const path& p, const path& base = current_path()); path canonical(const path& p, system::error_code& ec); path canonical(const path& p, const path& base, system::error_code& ec);Overview: Converts
p
, which must exist, to an absolute path that has no symbolic link, dot, or dot-dot elements.Returns: A canonical path that refers to the same file system object as
absolute(p,base)
. For the overload without abase
argument,base
iscurrent_path()
.Throws: As specified in Error reporting.
Remarks:
!exists(p)
is an error.[Note: Canonical pathnames allow security checking of a path (eg. does this path live in /home/goodguy or /home/badguy?) —end note]
void copy(const path& from, const path& to); void copy(const path& from, const path& to, system::error_code& ec);Effects: As if
file_status s(symlink_status(from[, ec
])); if(is_symlink(s)) copy_symlink(from, to[, ec
]); else if(is_directory(s)) copy_directory(from, to[, ec
]); else if(is_regular_file(s)) copy_file(from, to, copy_option::fail_if_exists[, ec
]); else Report error as specified in Error reporting.Throws: As specified in Error reporting.
void copy_directory(const path& from, const path& to); void copy_directory(const path& from, const path& to, system::error_code& ec);
This function is poorly named; it should probably be an overload of
create_directory
with an additional argument.Effects: Creates directory
to
, with attributes copied from directoryfrom
. The set of attributes copied is operating system dependent.
[Note: For ISO 9945/POSIX based operating systems the attributes are those copied by native API
stat(from.c_str(), &from_stat)
followed bymkdir(to.c_str(),from_stat.st_mode)
. For Windows based operating systems the attributes are those copied by native APICreateDirectoryExW(from.c_str(), to.c_str(), 0)
. —end note]Throws: As specified in Error reporting.
void copy_file(const path& from, const path& to); void copy_file(const path& from, const path& to, system::error_code& ec);Effects:
copy_file(from, to, copy_option::fail_if_exists
[, ec
])
.Throws: As specified in Error reporting.
void copy_file(const path& from, const path& to, copy_option option); void copy_file(const path& from, const path& to, copy_option option, system::error_code& ec);Effects: If
option == copy_option::
fail_if_exists && exists(to)
, an error is reported. Otherwise, the contents and attributes of the filefrom
resolves to are copied to the fileto
resolves to.Throws: As specified in Error reporting.
void copy_symlink(const path& existing_symlink, const path& new_symlink); void copy_symlink(const path& existing_symlink, const path& new_symlink, system::error_code& ec);Effects:
create_symlink(read_symlink(existing_symlink
[, ec
]), new_symlink
[, ec
])
.Throws: As specified in Error reporting.
bool create_directories(const path& p); bool create_directories(const path& p, system::error_code& ec);Effects: Establishes the postcondition by calling
create_directory()
for any element ofp
that does not exist.Postcondition:
is_directory(p)
Returns:
true
if a new directory was created, otherwisefalse
.Throws: As specified in Error reporting.
Complexity: O(n+1) where n is the number of elements of
p
that do not exist.bool create_directory(const path& p); bool create_directory(const path& p, system::error_code& ec);Effects: Establishes the postcondition by attempting to create the directory
p
resolves to, as if by ISO/IEC 9945mkdir()
with a second argument of S_IRWXU|S_IRWXG|S_IRWXO. Creation failure becausep
resolves to an existing directory shall not be treated as an error.Postcondition:
is_directory(p)
Returns:
true
if a new directory was created, otherwisefalse
.Throws: As specified in Error reporting.
void create_directory_symlink(const path& to, const path& new_symlink); void create_directory_symlink(const path& to, const path& new_symlink, system::error_code& ec);Effects: Establishes the postcondition, as if by ISO/IEC 9945
symlink()
.Postcondition:
new_symlink
resolves to a symbolic link file that contains an unspecified representation ofto
.Throws: As specified in Error reporting.
[Note: Some operating systems, such as Windows, require symlink creation to identify that the link is to a directory. Portable code should use
create_directory_symlink()
to create directory symlinks rather thancreate_symlink()
—end note][Note: Some operating systems do not support symbolic links at all or support them only for regular files. Some file systems do not support symbolic links regardless of the operating system - the FAT file system used on memory cards and flash drives, for example. —end note]
void create_hard_link(const path& to, const path& new_hard_link); void create_hard_link(const path& to, const path& new_hard_link, system::error_code& ec);Effects: Establishes the postcondition, as if by ISO/IEC 9945
link()
.Postcondition:
exists(to) && exists(
new_hard_link
) && equivalent(to,
new_hard_link
)
- The contents of the file or directory
to
resolves to are unchanged.Throws: As specified in Error reporting.
[Note: Some operating systems do not support hard links at all or support them only for regular files. Some file systems do not support hard links regardless of the operating system - the FAT file system used on memory cards and flash drives, for example. Some file systems limit the number of links per file. —end note]
void create_symlink(const path& to, const path& new_symlink); void create_symlink(const path& to, const path& new_symlink, system::error_code& ec);Effects: Establishes the postcondition, as if by ISO/IEC 9945
symlink()
.Postcondition:
new_symlink
resolves to a symbolic link file that contains an unspecified representation ofto
.Throws: As specified in Error reporting.
[Note: Some operating systems do not support symbolic links at all or support them only for regular files. Some file systems do not support symbolic links regardless of the operating system - the FAT system used on memory cards and flash drives, for example. —end note]
path current_path(); path current_path(system::error_code& ec);Returns: The current working directory path, as if by ISO/IEC 9945
getcwd()
.is_absolute()
is true for the returned path.Throws: As specified in Error reporting.
[Note: The
current_path()
name was chosen to emphasize that the return is a path, not just a single directory name.The current path as returned by many operating systems is a dangerous global variable. It may be changed unexpectedly by a third-party or system library functions, or by another thread. —end note]
void current_path(const path& p); void current_path(const path& p, system::error_code& ec);Effects: Establishes the postcondition, as if by ISO/IEC 9945
chdir()
.Postcondition:
equivalent(p, current_path())
.Throws: As specified in Error reporting.
[Note: The current path for many operating systems is a dangerous global state. It may be changed unexpectedly by a third-party or system library functions, or by another thread. —end note]
bool exists(file_status s) noexcept;Returns:
status_known(s) && s.type() != file_not_found
bool exists(const path& p); bool exists(const path& p, system::error_code& ec) noexcept;Returns:
exists(status(p))
orexists(status(p, ec))
, respectively. If ec != 0 and an errorThrows: As specified in Error reporting.
bool equivalent(const path& p1, const path& p2); bool equivalent(const path& p1, const path& p2, system::error_code& ec);
Effects: Determines
file_status s1
ands2
, as if bystatus(p1)
andstatus(p2)
, respectively.Returns:
true
, ifsf1 == sf2
andp1
andp2
resolve to the same file system entity, elsefalse
.Two paths are considered to resolve to the same file system entity if two candidate entities reside on the same device at the same location. This is determined as if by the values of the ISO/IEC 9945
stat
structure,
obtained as if bystat()
for the two paths, having equalst_dev
values and equalst_ino
values.[Note: ISO/IEC 9945 requires that "st_dev must be unique within a Local Area Network". Conservative ISO/IEC 9945 implementations may also wish to check for equal
st_size
andst_mtime
values. Windows implementations may useGetFileInformationByHandle()
as a surrogate forstat()
, and consider "same" to be equal values fordwVolumeSerialNumber
,nFileIndexHigh
,nFileIndexLow
,nFileSizeHigh
,nFileSizeLow
,ftLastWriteTime.dwLowDateTime
, andftLastWriteTime.dwHighDateTime
. —end note]Throws:
filesystem_error
if(!exists(s1) && !exists(s2)) || (is_other(s1) && is_other(s2))
, otherwise as specified in Error reporting.uintmax_t file_size(const path& p); uintmax_t file_size(const path& p, system::error_code& ec);Returns: If
exists(p) && is_regular_file(p)
, the size in bytes of the filep
resolves to, determined as if by the value of the ISO/IEC 9945stat
structure memberst_size
obtained as if by ISO/IEC 9945stat()
. Otherwise,static_cast<uintmax_t>(-1)
.Throws: As specified in Error reporting.
uintmax_t hard_link_count(const path& p); uintmax_t hard_link_count(const path& p, system::error_code& ec);Returns: The number of hard links for
p
.Throws: As specified in Error reporting.
const path& initial_path(); const path& initial_path(system::error_code& ec
);Returns:
current_path()
as of the first call toinitial_path()
.[Note:
initial_path()
is not thread safe, and may return an undesirable result if called subsequent to a change to the current directory. These problems can be avoided by callinginitial_path()
immediately on entry to main(). —end note]Throws: For the first call, as specified in Error reporting. Subsequent calls throw nothing.
boolis_directory
(file_status s) noexcept;Returns:
s.type() == directory_file
bool is_directory(const path& p); bool is_directory(const path& p, system::error_code& ec) noexcept;
Returns:
is_directory(status(p))
oris_directory(status(p, ec))
, respectively.Throws:
filesystem_error
; overload witherror_code&
throws nothing.bool is_empty(const path& p); bool is_empty(const path& p, system::error_code& ec);
Effects: Determines
file_status s
, as if bystatus(p, ec)
.Returns:
is_directory(s)
? directory_iterator(p) == directory_iterator()
: file_size(p) == 0;boolis_regular_file
(file_status s) noexcept;Returns:
s.type() == regular_file
bool is_regular_file(const path& p);
Returns:
is_regular_file(status(p))
.Throws:
filesystem_error
ifstatus(p)
would throwfilesystem_error.
bool is_regular_file(const path& p, system::error_code& ec) noexcept;
Effects: Sets
ec
as if bystatus(p, ec)
. [Note:status_error
,file_not_found
andtype_unknown
cases setec
to error values. To distinguish between cases, call thestatus
function directly. —end note]Returns:
is_regular_file(status(p, ec))
.bool is_other(file_status s) noexcept;Returns:
return exists(s) && !is_regular_file(s) && !is_directory(s) && !is_symlink(s)
bool is_other(const path& p); bool is_other(const path& p, system::error_code& ec) noexcept;
Returns:
is_other(status(p))
oris_other(status(p, ec))
, respectively.Throws:
filesystem_error
; overload witherror_code&
throws nothing.bool is_symlink(file_status s) noexcept;Returns:
s.type() == symlink_file
bool is_symlink(const path& p); bool is_symlink(const path& p, system::error_code& ec) noexcept;
Returns:
is_symlink(symlink_status(p))
oris_symlink(symlink_status(p, ec))
, respectively.Throws:
filesystem_error
; overload witherror_code&
throws nothing.std::time_t last_write_time(const path& p); std::time_t last_write_time(const path& p, system::error_code& ec
);Returns: The time of last data modification of
p
, determined as if by the value of the ISO/IEC 9945stat
structure memberst_mtime
obtained as if by ISO/IEC 9945stat()
.Throws: As specified in Error reporting.
void last_write_time(const path& p, const std::time_t new_time); void last_write_time(const path& p, const std::time_t new_time, system::error_code& ec
);Effects: Sets the time of last data modification of the file resolved to by
p
tonew_time
, as if by ISO/IEC 9945stat()
followed by ISO/IEC 9945utime()
.Throws: As specified in Error reporting.
[Note: A postcondition of
last_write_time(p) == new_time
is not specified since it might not hold for file systems with coarse time granularity. —end note]void permissions(const path& p, perms prms); void permissions(const path& p, perms prms, system::error_code& ec);Requires:
!((prms & add_perms) && (prms & remove_perms))
.Effects: Applies the effective permissions bits from
prms
to the filep
resolves to, as if by ISO/IEC 9945fchmodat()
. The effective permission bits are determined as specified by the following table.
bits present in prms
Effective bits applied Neither add_perms
norremove_perms
prms & perms_mask
add_perms
status(p).permissions() | (prms & perms_mask)
remove_perms
status(p)
.permissions() & ~(prms & perms_mask)
[Note: Conceptually permissions are viewed as bits, but the actual implementation may use some other mechanism. -- end note]
Throws: As specified in Error reporting.
path read_symlink(const path& p); path read_symlink(const path& p, system::error_code& ec);Returns: If
p
resolves to a symbolic link, apath
object containing the contents of that symbolic link. Otherwise an emptypath
object.Throws: As specified in Error reporting. [Note: It is an error if
p
does not resolve to a symbolic link. —end note]path relative(const path& p, system::error_code& ec);Returns:
relative(p, current_path(), ec)
.Throws: As specified in Error reporting.
path relative(const path& p, const path& base=current_path()); path relative(const path& p, const path& base, system::error_code& ec);Overview: Returns
p
made relative tobase
. Treats empty or identical paths as corner cases, not errors. Resolves symlinks and normalizes bothp
andbase
before other processing.Returns:
weakly_canonical(p).lexically_relative(weakly_canonical(base))
. The second form returnspath()
if an error occurs.Throws: As specified in Error reporting.
bool remove(const path& p); bool remove(const path& p, system::error_code& ec);Effects: If
exists(symlink_status(p,ec))
, it is removed as if by ISO/IEC 9945remove()
.[Note: A symbolic link is itself removed, rather than the file it resolves to being removed. —end note]
Postcondition:
!exists(symlink_status(p))
.Returns:
false
if p did not exist in the first place, otherwisetrue
.Throws: As specified in Error reporting.
uintmax_t remove_all(const path& p); uintmax_t remove_all(const path& p, system::error_code& ec);Effects: Recursively deletes the contents of p if it exists, then deletes file
p
itself, as if by ISO/IEC 9945remove()
.[Note: A symbolic link is itself removed, rather than the file it resolves to being removed. —end note]
Postcondition:
!exists(p)
Returns: The number of files removed.
Throws: As specified in Error reporting.
void rename(const path& old_p, const path& new_p); void rename(const path& old_p, const path& new_p, system::error_code& ec);Effects: Renames
old_p
tonew_p
, as if by ISO/IEC 9945rename()
.[Note: If
old_p
andnew_p
resolve to the same existing file, no action is taken. Otherwise, ifnew_p
resolves to an existing non-directory file, it is removed, while ifnew_p
resolves to an existing directory, it is removed if empty on ISO/IEC 9945 but is an error on Windows. A symbolic link is itself renamed, rather than the file it resolves to being renamed. —end note]Throws: As specified in Error reporting.
void resize_file(const path& p, uintmax_t new_size); void resize_file(const path& p, uintmax_t new_size, system::error_code& ec);Postcondition:
file_size() == new_size
.Throws: As specified in Error reporting.
Remarks: Achieves its postconditions as if by ISO/IEC 9945
truncate()
.space_info space(const path& p); space_info space(const path& p, system::error_code& ec);Returns: An object of type
space_info
. The value of thespace_info
object is determined as if by using ISO/IEC 9945statvfs()
to obtain a ISO/IEC 9945 structstatvfs
, and then multiplying itsf_blocks
,f_bfree
, andf_bavail
members by itsf_frsize
member, and assigning the results to thecapacity
,free
, andavailable
members respectively. Any members for which the value cannot be determined shall be set to -1.Throws: As specified in Error reporting.
file_status status(const path& p);Effects: As if:
system::error_code ec; file_status result = status(p, ec); if (result == status_error) throw filesystem_error(implementation-supplied-message, p, ec); return result;Returns: See above.
Throws:
filesystem_error
. [Note:result
values offile_status(file_not_found)
andfile_status(type_unknown)
are not considered failures and do not cause an exception to be thrown. —end note]file_status status(const path& p, system::error_code& ec) noexcept;Effects:
If possible, determines the attributes of the file
If, during attribute determination, the underlying file system API reports an error, setsp
resolves to, as if by ISO/IEC 9945stat()
.ec
to indicate the specific error reported. Otherwise,ec.clear()
.[Note: This allows users to inspect the specifics of underlying API errors even when the value returned by
status()
is notfile_status(status_error)
. —end note]Returns:
If
ec != error_code()
:
- If the specific error indicates that
p
cannot be resolved because some element of the path does not exist, returnfile_status(file_not_found)
. [Note: ISO/IEC 9945 errors that indicate this are ENOENT or ENOTDIR. Windows equivalents include ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, ERROR_INVALID_NAME, ERROR_INVALID_PARAMETER, ERROR_BAD_PATHNAME, and ERROR_BAD_NETPATH. -- end note]
- Otherwise, if the specific error indicates that
p
can be resolved but the attributes cannot be determined, returnfile_status(type_unknown)
. [Note: For example, Windows ERROR_SHARING_VIOLATION errors. For ISO/IEC 9945, the case never arises. —end note]
- Otherwise, return
file_status(status_error)
.[Note: These semantics distinguish between
p
being known not to exist,p
existing but not being able to determine its attributes, and there being an error that prevents even knowing ifp
exists. These distinctions are important to some use cases. —end note]Otherwise,
- If the attributes indicate a regular file, as if by ISO/IEC 9945 S_ISREG(), return
file_status(regular_file)
. [Note:regular_file
implies appropriate<fstream>
operations would succeed, assuming no hardware, permission, access, or file system race errors. Lack ofregular_file
does not necessarily imply<fstream>
operations would fail on a directory. —end note]
- Otherwise, if the attributes indicate a directory, as if by ISO/IEC 9945 S_ISDIR(), return
file_status(directory_file)
. [Note:directory_file
impliesdirectory_iterator(p)
would succeed. —end note]
- Otherwise, if the attributes indicate a block special file, as if by ISO/IEC 9945 S_ISBLK(), return
file_status(block_file)
.
- Otherwise, if the attributes indicate a character special file, as if by ISO/IEC 9945 S_ISCHR(), return
file_status(character_file)
.
- Otherwise, if the attributes indicate a fifo or pipe file, as if by ISO/IEC 9945 S_ISFIFO(), return
file_status(fifo_file)
.
- Otherwise, if the attributes indicate a socket, as if by ISO/IEC 9945 S_ISSOCK(), return
file_status(socket_file)
.
- Otherwise, return
file_status(type_unknown)
.Remarks: If a symbolic link is encountered during pathname resolution, pathname resolution continues using the contents of the symbolic link.
bool status_known(file_status s) noexcept;Returns:
s.type() != status_error
file_status symlink_status(const path& p); file_status symlink_status(const path& p, system::error_code& ec) noexcept;Effects: Same as status(), above, except that the attributes of
p
are determined as if by ISO/IEC 9945lstat()
.Returns: Same as status(), above, except that if the attributes indicate a symbolic link, as if by ISO/IEC 9945 S_ISLNK(), return
file_status(symlink_file)
.Remarks: Pathname resolution terminates if
p
names a symbolic link.Throws:
filesystem_error
; overload witherror_code&
throws nothing.path system_complete(const path& p); path system_complete(const path& p, system::error_code& ec);Effects: Composes an absolute path from
p
, using the same rules used by the operating system to resolve a path passed as the filename argument to standard library open functions.Returns: The composed path.
Postcondition: For the returned path,
rp,
rp.is_absolute()
is true.Throws: As specified in Error reporting.
[Note: For ISO/IEC 9945,
system_complete(p)
has the same semantics ascomplete(p, current_path())
.For Windows,
system_complete(p)
has the same semantics ascomplete(ph, current_path())
ifp.is_absolute() || !p.has_root_name()
orp
andbase
have the sameroot_name()
. Otherwise it acts likecomplete(p, kinky)
, wherekinky
is the current directory for thep.root_name()
drive. This will be the current directory of that drive the last time it was set, and thus may be residue left over from a prior program run by the command processor! Although these semantics are often useful, they are also very error-prone.See complete() note for usage suggestions. —end note]
path temp_directory_path(); path temp_directory_path(system::error_code& ec);Returns: A directory path suitable for temporary files under the conventions of the operating system. The specifics of how this path is determined are implementation defined. An error shall be reported if
!exists(p) || !is_directory(p)
, wherep
is the path to be returned.ISO/IEC 9945: The path supplied by the first environment variable found in the list TMPDIR, TMP, TEMP, TEMPDIR. If none of these are found,
"/tmp"
, or, if macro__ANDROID__
is defined,"/data/local/tmp"
.Windows: The path reported by the Windows
GetTempPath
API function.Throws: As specified in Error reporting.
[Note: The
temp_directory_path()
name was chosen to emphasize that the return is a path, not just a single directory name. —end note]path unique_path(const path& model="%%%%-%%%%-%%%%-%%%%"); path unique_path(const path& model, system::error_code& ec);The
unique_path
function generates a path name suitable for creating temporary files, including directories. The name is based on a model that uses the percent sign character to specify replacement by a random hexadecimal digit. [Note: The more bits of randomness in the generated path name, the less likelihood of prior existence or being guessed. Each replacement hexadecimal digit in the model adds four bits of randomness. The default model thus provides 64 bits of randomness. This is sufficient for most applications. —end note]Returns: A path identical to
model
, except that each occurrence of a percent sign character is replaced by a random hexadecimal digit character in the range 0-9, a-f.Throws: As specified in Error reporting.
Remarks: Implementations are encouraged to obtain the required randomness via a cryptographically secure pseudo-random number generator, such as one provided by the operating system. [Note: Such generators may block until sufficient entropy develops. —end note]
path weakly_canonical(const path& p); path weakly_canonical(const path& p, system::error_code& ec);Overview: Returns
p
with symlinks resolved and the result normalized.Returns: A path composed of the result of calling the
canonical
function on a path composed of the leading elements ofp
that exist, if any, followed by the elements ofp
that do not exist, if any.Postcondition: The returned path is in normal form.
Remarks: Uses
operator/=
to compose the returned path. Uses thestatus
function to determine existence.Remarks: Implementations are encouraged to avoid unnecessary normalization such as when
canonical
has already been called on the entirety ofp
.Throws: As specified in Error reporting.
File streams - <boost/filesystem/fstream.hpp>
Replacements are provided for the file stream classes from the C++ standard library's
<fstream>
header. These replacement classes publicly inherit from the standard library classes. In the Boost.Filesystem version, constructors and open functions takeconst path&
arguments instead ofconst char*
arguments. There are no other differences in syntax or semantics.namespace boost { namespace filesystem { template < class charT, class traits = std::char_traits<charT> > class basic_filebuf : public std::basic_filebuf<charT,traits> { public: basic_filebuf<charT,traits>* open(const path& p, std::ios_base::openmode mode); }; template < class charT, class traits = std::char_traits<charT> > class basic_ifstream : public std::basic_ifstream<charT,traits> { public: explicit basic_ifstream(const path& p, std::ios_base::openmode mode=std::ios_base::in) void open(const path& p, std::ios_base::openmode mode=std::ios_base::in); }; template < class charT, class traits = std::char_traits<charT> > class basic_ofstream : public std::basic_ofstream<charT,traits> { public: explicit basic_ofstream(const path& p, std::ios_base::openmode mode=std::ios_base::out); void open(const path& p, std::ios_base::openmode mode=std::ios_base::out); }; template < class charT, class traits = std::char_traits<charT> > class basic_fstream : public std::basic_fstream<charT,traits> { public: explicit basic_fstream(const path& p, std::ios_base::openmode mode=std::ios_base::in | std::ios_base::out); void open(const path& p, std::ios_base::openmode mode=std::ios_base::in | std::ios_base::out); }; typedef basic_filebuf<char> filebuf; typedef basic_ifstream<char> ifstream; typedef basic_ofstream<char> ofstream; typedef basic_fstream<char> fstream; typedef basic_filebuf<wchar_t> wfilebuf; typedef basic_ifstream<wchar_t> wifstream; typedef basic_fstream<wchar_t> wfstream; typedef basic_ofstream<wchar_t> wofstream; } // namespace filesystem } // namespace boostPath decomposition table
The table is generated by a program compiled with the Boost implementation.
Shaded entries indicate cases where ISO/IEC 9945 (POSIX) and Windows implementations yield different results. The top value is the ISO/IEC 9945 result and the bottom value is the Windows result.
Constructor
argumentIteration
over
Elementsstring()
generic_
string()root_
path()root_
name()root_
directory()relative_
path()parent_
path()filename()
empty empty empty empty empty empty empty empty empty empty .
.
.
.
empty empty empty .
empty .
..
..
..
..
empty empty empty ..
empty ..
foo
foo
foo
foo
empty empty empty foo
empty foo
/
/
/
/
/
empty /
empty empty /
/foo
/,foo
/foo
/foo
/
empty /
foo
/
foo
foo/
foo,.
foo/
foo/
empty empty empty foo/
foo
.
/foo/
/,foo,.
/foo/
/foo/
/
empty /
foo/
/foo
.
foo/bar
foo,bar
foo/bar
foo/bar
empty empty empty foo/bar
foo
bar
/foo/bar
/,foo,bar
/foo/bar
/foo/bar
/
empty /
foo/bar
/foo
bar
//net
//net
//net
//net
//net
//net
empty empty empty //net
//net/foo
//net,/,foo
//net/foo
//net/foo
//net/
//net
/
foo
//net/
foo
///foo///
/,foo,.
///foo///
///foo///
/
empty /
foo///
///foo
.
///foo///bar
/,foo,bar
///foo///bar
///foo///bar
/
empty /
foo///bar
///foo
bar
/.
/,.
/.
/.
/
empty /
.
/
.
./
.,.
./
./
empty empty empty ./
.
.
/..
/,..
/..
/..
/
empty /
..
/
..
../
..,.
../
../
empty empty empty ../
..
.
foo/.
foo,.
foo/.
foo/.
empty empty empty foo/.
foo
.
foo/..
foo,..
foo/..
foo/..
empty empty empty foo/..
foo
..
foo/./
foo,.,.
foo/./
foo/./
empty empty empty foo/./
foo/.
.
foo/./bar
foo,.,bar
foo/./bar
foo/./bar
empty empty empty foo/./bar
foo/.
bar
foo/..
foo,..
foo/..
foo/..
empty empty empty foo/..
foo
..
foo/../
foo,..,.
foo/../
foo/../
empty empty empty foo/../
foo/..
.
foo/../bar
foo,..,bar
foo/../bar
foo/../bar
empty empty empty foo/../bar
foo/..
bar
c:
c:
c:
c:
empty c:
empty c:
empty c:
emptyempty c:
c:/
c:,.
c:,/
c:/
c:/
empty c:/
empty c:
empty /
c:/
emptyc:
.
/
c:foo
c:foo
c:,foo
c:foo
c:foo
empty c:
empty c:
empty c:foo
foo
empty c:
c:foo
foo
c:/foo
c:,foo
c:,/,foo
c:/foo
c:/foo
empty c:/
empty c:
empty /
c:/foo
foo
c:
c:/
foo
c:foo/
c:foo,.
c:,foo,.
c:foo/
c:foo/
empty c:
empty c:
empty c:foo/
foo/
c:foo
.
c:/foo/
c:,foo,.
c:,/,foo,.
c:/foo/
c:/foo/
empty c:/
empty c:
empty /
c:/foo/
foo/
c:/foo
.
c:/foo/bar
c:,foo,bar
c:,/,foo,bar
c:/foo/bar
c:/foo/bar
empty c:/
empty c:
empty /
c:/foo/bar
foo/bar
c:/foo
bar
prn:
prn:
prn:
prn:
empty prn:
empty prn:
empty prn:
emptyempty prn:
c:\
c:\
c:,/
c:\
c:\
c:/
empty c:\
empty c:
empty \
c:\
emptyempty c:
c:\
\
c:foo
c:foo
c:,foo
c:foo
c:foo
empty c:
empty c:
empty c:foo
foo
empty c:
c:foo
foo
c:\foo
c:\foo
c:,/,foo
c:\foo
c:\foo
c:/foo
empty c:\
empty c:
empty \
c:\foo
foo
empty c:\
c:\foo
foo
c:foo\
c:foo\
c:,foo,.
c:foo\
c:foo\
c:foo/
empty c:
empty c:
empty c:foo\
foo\
empty c:foo
c:foo\
.
c:\foo\
c:\foo\
c:,/,foo,.
c:\foo\
c:\foo\
c:/foo/
empty c:\
empty c:
empty \
c:\foo\
foo\
empty c:\foo
c:\foo\
.
c:\foo/
c:\foo,.
c:,/,foo,.
c:\foo/
c:\foo/
c:/foo/
empty c:\
empty c:
empty \
c:\foo/
foo/
c:\foo
.
c:/foo\bar
c:,foo\bar
c:,/,foo,bar
c:/foo\bar
c:/foo\bar
c:/foo/bar
empty c:/
empty c:
empty /
c:/foo\bar
foo\bar
c:
c:/foo
foo\bar
bar
Warning: Long paths on Windows and the extended-length \\?\ prefix
The Microsoft Windows "Maximum Path Length Limitation" specifies:
In the Windows API (with some exceptions ...), the maximum length for a path is MAX_PATH, which is defined as 260 characters.
The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters. ... To specify an extended-length path, use the "\\?\" prefix. For example, "\\?\D:\very long path". [C++ string literals require backslashes be doubled, of course.]
Because most Boost.Filesystem operational functions just pass the contents of a class path object to the Windows API, they do work with the extended-length prefixes. But some won't work, because to the limitations imposed by Windows. Read the following cautions carefully!
Cautions for paths with extended-length prefixes
- Individual components of a path are still are limited to whatever is supported for the particular filesystem, commonly 255 characters.
- Only backslashes only are acceptable as directory separators. Slashes are not treated as separators.
- All paths must be absolute - relative paths are not allowed.
- Once an absolute path grows beyond 260 characters, it is essentially poisoned and all operations must use extended-length prefixes. So even a simple operation like
create_directory("a")
will fail if the absolute path of the resulting directory would exceed 260 characters.- Certain Boost.Filesystem functions that decompose their argument path and then work on individual relative directories or files will not work properly with extended-length prefix paths.
Acknowledgements
This Filesystem Library is dedicated to my wife, Sonda, who provided the support necessary to see both a trial implementation and the proposal itself through to completion. She gave me the strength to continue after a difficult year of cancer treatment in the middle of it all.
Many people contributed technical comments, ideas, and suggestions to the Boost Filesystem Library. See http://www.boost.org/libs/filesystem/doc/index.htm#Acknowledgements.
Dietmar Kuehl contributed the original Boost Filesystem Library directory_iterator design. Peter Dimov, Walter Landry, Rob Stewart, and Thomas Witt were particularly helpful in refining the library.
The create_directories, extension, basename, and replace_extension functions were developed by Vladimir Prus. The temp_directory_path function was contributed by Jeff Flinn. David Svoboda suggested the canonical function and provided psuedo-code.
Howard Hinnant and John Maddock reviewed a draft of the version 2 proposal, and identified a number of mistakes or weaknesses, resulting in a more polished final document.
Peter Dimov suggested a single class path, with member templates to adapt to multiple string types. His idea became the basis for the version 3 path design.
References
[ISO/IEC 9945] ISO/IEC 9945:2003, IEEE Std 1003.1-2001, and The Open Group Base Specifications, Issue 6. Also known as The Single Unix® Specification, Version 3. Available from each of the organizations involved in its creation. For example, read online or download from www.unix.org/single_unix_specification/. The ISO JTC1/SC22/WG15 - POSIX homepage is www.open-std.org/jtc1/sc22/WG15/ [Abrahams] Dave Abrahams, Error and Exception Handling, www.boost.org/more/error_handling.html
© Copyright Beman Dawes, 2002, 2006, 2007, 2009, 2010, 2011
Distributed under the Boost Software License, Version 1.0. See www.boost.org/LICENSE_1_0.txt
Revised 01 December 2015