Menu

- Learn
- Documentation
  - Language Reference
  - Library Reference
  - Command-line Reference
  - Feature Overview
  - Articles
- Downloads
- Packages
- Community
  - Blog
  - Orgs using D
  - Twitter
  - Calendar
  - Forums
  - IRC
  - Community Discord
  - Wiki
  - GitHub
  - Issues
  - Get involved
  - Contributors
  - Foundation
  - Security Team
  - Donate
  - Sponsors
- Resources
  - Tour
  - Books
  - Tutorials
  - Tools
  - Editors
  - IDEs
  - run.dlang.io
  - Visual D
  - Acknowledgments
  - D Style
  - Glossary
  - Sitemap

Search
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

# std.file

Utilities for manipulating files and scanning directories. Functions in this module handle files as a unit, e.g., read or write one file at a time. For opening files and manipulating them via handles refer to module std.stdio.

Category | Functions
--- | ---
General | exists isDir isFile isSymlink rename thisExePath
Directories | chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir
Files | append copy read readText remove slurp write
Symlinks | symlink readLink
Attributes | attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes
Timestamp | getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged
Other | DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace

See Also:
The official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.
License:
Boost License 1.0.
Authors:
Walter Bright, Andrei Alexandrescu, Jonathan M Davis

Source std/file.d

class `FileException`: object.Exception;
  Exception thrown for file I/O errors.
  Examples:

      import std.exception : assertThrown;

      assertThrown!FileException("non.existing.file.".readText);

  immutable uint `errno`;
    OS error code.
  pure @safe this(scope const(char)[] `name`, scope const(char)[] `msg`, string `file` = __FILE__, size_t `line` = __LINE__);
    Constructor which takes an error message.
    Parameters:

    const(char)[] `name` | Name of file for which the error occurred.
    const(char)[] `msg` | Message describing the error.
    string `file` | The file where the error occurred.
    size_t `line` | The line where the error occurred.

  @trusted this(scope const(char)[] `name`, uint `errno` = .`errno`, string `file` = __FILE__, size_t `line` = __LINE__);
    Constructor which takes the error number (GetLastError in Windows, errno in POSIX).
    Parameters:

    const(char)[] `name` | Name of file for which the error occurred.
    uint `errno` | The error number.
    string `file` | The file where the error occurred. Defaults to __FILE__.
    size_t `line` | The line where the error occurred. Defaults to __LINE__.

void[] `read`(R)(R `name`, size_t `upTo` = size_t.max)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
void[] `read`(R)(auto ref R `name`, size_t `upTo` = size_t.max)
if (isConvertibleToString!R);
  Read entire contents of file `name` and returns it as an untyped array. If the file size is larger than `upTo`, only `upTo` bytes are read.
  Parameters:

  R `name` | string or range of characters representing the file name
  size_t `upTo` | if present, the maximum number of bytes to read

  Returns:
  Untyped array of bytes read.
  Throws:
  FileException on error.
  Examples:

      import std.utf : byChar;
      scope(exit)
      {
          assert(exists(deleteme));
          remove(deleteme);
      }

      std.file.write(deleteme, "1234"); // deleteme is the name of a temporary file
      writeln(read(deleteme, 2)); // "12"
      writeln(read(deleteme.byChar)); // "1234"
      writeln((cast(const(ubyte)[])read(deleteme)).length); // 4

S `readText`(S = string, R)(auto ref R `name`)
if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R)));
  Reads and validates (using std.utf.validate) a text file. S can be an array of any character type. However, no width or endian conversions are performed. So, if the width or endianness of the characters in the given file differ from the width or endianness of the element type of S, then validation will fail.
  Parameters:

  S | the string type of the file
  R `name` | string or range of characters representing the file name

  Returns:
  Array of characters read.
  Throws:
  FileException if there is an error reading the file, std.utf.UTFException on UTF decoding error.
  Examples:
  Read file with UTF-8 text.

      write(deleteme, "abc"); // deleteme is the name of a temporary file
      scope(exit) remove(deleteme);
      string content = readText(deleteme);
      writeln(content); // "abc"

void `write`(R)(R `name`, const void[] `buffer`)
if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R);
void `write`(R)(auto ref R `name`, const void[] `buffer`)
if (isConvertibleToString!R);
  Write `buffer` to file `name`.
  Creates the file if it does not already exist.
  Parameters:

  R `name` | string or range of characters representing the file name
  void[] `buffer` | data to be written to file

  Throws:
  FileException on error.
  See Also:
  std.stdio.toFile
  Examples:

      scope(exit)
      {
          assert(exists(deleteme));
          remove(deleteme);
      }

      int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
      write(deleteme, a); // deleteme is the name of a temporary file
      const bytes = read(deleteme);
      const fileInts = () @trusted { return cast(int[]) bytes; }();
      writeln(fileInts); // a

void `append`(R)(R `name`, const void[] `buffer`)
if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R);
void `append`(R)(auto ref R `name`, const void[] `buffer`)
if (isConvertibleToString!R);
  Appends `buffer` to file `name`.
  Creates the file if it does not already exist.
  Parameters:

  R `name` | string or range of characters representing the file name
  void[] `buffer` | data to be appended to file

  Throws:
  FileException on error.
  Examples:

      scope(exit)
      {
          assert(exists(deleteme));
          remove(deleteme);
      }

      int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
      write(deleteme, a); // deleteme is the name of a temporary file
      int[] b = [ 13, 21 ];
      append(deleteme, b);
      const bytes = read(deleteme);
      const fileInts = () @trusted { return cast(int[]) bytes; }();
      writeln(fileInts); // a ~ b

void `rename`(RF, RT)(RF `from`, RT `to`)
if ((isSomeFiniteCharInputRange!RF || isSomeString!RF) && !isConvertibleToString!RF && (isSomeFiniteCharInputRange!RT || isSomeString!RT) && !isConvertibleToString!RT);
void `rename`(RF, RT)(auto ref RF `from`, auto ref RT `to`)
if (isConvertibleToString!RF || isConvertibleToString!RT);
  Rename file `from` to `to`, moving it between directories if required. If the target file exists, it is overwritten.
  It is not possible to rename a file across different mount points or drives. On POSIX, the operation is atomic. That means, if `to` already exists there will be no time period during the operation where `to` is missing. See manpage for rename for more details.
  Parameters:

  RF `from` | string or range of characters representing the existing file name
  RT `to` | string or range of characters representing the target file name

  Throws:
  FileException on error.
  Examples:

      auto t1 = deleteme, t2 = deleteme~"2";
      scope(exit) foreach (t; [t1, t2]) if (t.exists) t.remove();

      t1.write("1");
      t1.rename(t2);
      writeln(t2.readText); // "1"

      t1.write("2");
      t1.rename(t2);
      writeln(t2.readText); // "2"

void `remove`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
void `remove`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  Delete file `name`.
  Parameters:

  R `name` | string or range of characters representing the file name

  Throws:
  FileException on error.
  Examples:

      import std.exception : assertThrown;

      deleteme.write("Hello");
      writeln(deleteme.readText); // "Hello"

      deleteme.remove;
      assertThrown!FileException(deleteme.readText);

ulong `getSize`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
ulong `getSize`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  Get size of file `name` in bytes.
  Parameters:

  R `name` | string or range of characters representing the file name

  Returns:
  The size of file in bytes.
  Throws:
  FileException on error (e.g., file not found).
  Examples:

      scope(exit) deleteme.remove;

      // create a file of size 1
      write(deleteme, "a");
      writeln(getSize(deleteme)); // 1

      // create a file of size 3
      write(deleteme, "abc");
      writeln(getSize(deleteme)); // 3

void `getTimes`(R)(R `name`, out SysTime `accessTime`, out SysTime `modificationTime`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
void `getTimes`(R)(auto ref R `name`, out SysTime `accessTime`, out SysTime `modificationTime`)
if (isConvertibleToString!R);
  Get the access and modified times of file or folder `name`.
  Parameters:

  R `name` | File/Folder name to get times for.
  SysTime `accessTime` | Time the file/folder was last accessed.
  SysTime `modificationTime` | Time the file/folder was last modified.

  Throws:
  FileException on error.
  Examples:

      import std.datetime : abs, SysTime;

      scope(exit) deleteme.remove;
      write(deleteme, "a");

      SysTime accessTime, modificationTime;

      getTimes(deleteme, accessTime, modificationTime);

      import std.datetime : Clock, seconds;
      auto currTime = Clock.currTime();
      enum leeway = 5.seconds;

      auto diffAccess = accessTime - currTime;
      auto diffModification = modificationTime - currTime;
      assert(abs(diffAccess) <= leeway);
      assert(abs(diffModification) <= leeway);

void `getTimesWin`(R)(R `name`, out SysTime `fileCreationTime`, out SysTime `fileAccessTime`, out SysTime `fileModificationTime`)
if (isSomeFiniteCharInputRange!R || isConvertibleToString!R);
  This function is Windows-Only.
  Get creation/access/modified times of file `name`.
  This is the same as getTimes except that it also gives you the file creation time - which isn't possible on POSIX systems.
  Parameters:

  R `name` | File name to get times for.
  SysTime `fileCreationTime` | Time the file was created.
  SysTime `fileAccessTime` | Time the file was last accessed.
  SysTime `fileModificationTime` | Time the file was last modified.

  Throws:
  FileException on error.
void `setTimes`(R)(R `name`, SysTime `accessTime`, SysTime `modificationTime`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
void `setTimes`(R)(auto ref R `name`, SysTime `accessTime`, SysTime `modificationTime`)
if (isConvertibleToString!R);
  Set access/modified times of file or folder `name`.
  Parameters:

  R `name` | File/Folder name to get times for.
  SysTime `accessTime` | Time the file/folder was last accessed.
  SysTime `modificationTime` | Time the file/folder was last modified.

  Throws:
  FileException on error.
  Examples:

      import std.datetime : DateTime, hnsecs, SysTime;

      scope(exit) deleteme.remove;
      write(deleteme, "a");

      SysTime accessTime = SysTime(DateTime(2010, 10, 4, 0, 0, 30));
      SysTime modificationTime = SysTime(DateTime(2018, 10, 4, 0, 0, 30));
      setTimes(deleteme, accessTime, modificationTime);

      SysTime accessTimeResolved, modificationTimeResolved;
      getTimes(deleteme, accessTimeResolved, modificationTimeResolved);

      writeln(accessTime); // accessTimeResolved
      writeln(modificationTime); // modificationTimeResolved

SysTime `timeLastModified`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
SysTime `timeLastModified`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  Returns the time that the given file was last modified.
  Parameters:

  R `name` | the name of the file to check

  Returns:
  A std.datetime.systime.SysTime.
  Throws:
  FileException if the given file does not exist.
  Examples:

      import std.datetime : abs, DateTime, hnsecs, SysTime;
      scope(exit) deleteme.remove;

      import std.datetime : Clock, seconds;
      auto currTime = Clock.currTime();
      enum leeway = 5.seconds;
      deleteme.write("bb");
      assert(abs(deleteme.timeLastModified - currTime) <= leeway);

SysTime `timeLastModified`(R)(R `name`, SysTime `returnIfMissing`)
if (isSomeFiniteCharInputRange!R);
  Returns the time that the given file was last modified. If the file does not exist, returns `returnIfMissing`.
  A frequent usage pattern occurs in build automation tools such as make or ant. To check whether file target must be rebuilt from file source (i.e., target is older than source or does not exist), use the comparison below. The code throws a FileException if source does not exist (as it should). On the other hand, the SysTime.min default makes a non-existing target seem infinitely old so the test correctly prompts building it.
  Parameters:

  R `name` | The name of the file to get the modification time for.
  SysTime `returnIfMissing` | The time to return if the given file does not exist.

  Returns:
  A std.datetime.systime.SysTime.

  Example

      if (source.timeLastModified >= target.timeLastModified(SysTime.min))
      {
          // must (re)build
      }
      else
      {
          // target is up-to-date
      }

  Examples:

      import std.datetime : SysTime;

      writeln("file.does.not.exist".timeLastModified(SysTime.min)); // SysTime.min

      auto source = deleteme ~ "source";
      auto target = deleteme ~ "target";
      scope(exit) source.remove, target.remove;

      source.write(".");
      assert(target.timeLastModified(SysTime.min) < source.timeLastModified);
      target.write(".");
      assert(target.timeLastModified(SysTime.min) >= source.timeLastModified);

pure nothrow SysTime `timeLastModified`()(auto ref stat_t `statbuf`);
  This function is POSIX-Only.
  Returns the time that the given file was last modified.
  Parameters:

  stat_t `statbuf` | stat_t retrieved from file.

pure nothrow SysTime `timeLastAccessed`()(auto ref stat_t `statbuf`);
  This function is POSIX-Only.
  Returns the time that the given file was last accessed.
  Parameters:

  stat_t `statbuf` | stat_t retrieved from file.

pure nothrow SysTime `timeStatusChanged`()(auto ref stat_t `statbuf`);
  This function is POSIX-Only.
  Returns the time that the given file was last changed.
  Parameters:

  stat_t `statbuf` | stat_t retrieved from file.

bool `exists`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
bool `exists`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  Determine whether the given file (or directory) exists.
  Parameters:

  R `name` | string or range of characters representing the file name

  Returns:
  true if the file name specified as input exists
  Examples:

      auto f = deleteme ~ "does.not.exist";
      assert(!f.exists);

      f.write("hello");
      assert(f.exists);

      f.remove;
      assert(!f.exists);

uint `getAttributes`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
uint `getAttributes`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  Returns the attributes of the given file.
  Note that the file attributes on Windows and POSIX systems are completely different. On Windows, they're what is returned by GetFileAttributes, whereas on POSIX systems, they're the st_mode value which is part of the stat struct gotten by calling the stat function.
  On POSIX systems, if the given file is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link.
  Parameters:

  R `name` | The file to get the attributes of.

  Returns:
  The attributes of the file as a uint.
  Throws:
  FileException on error.
  Examples:
  getAttributes with a file

      import std.exception : assertThrown;

      auto f = deleteme ~ "file";
      scope(exit) f.remove;

      assert(!f.exists);
      assertThrown!FileException(f.getAttributes);

      f.write(".");
      auto attributes = f.getAttributes;
      assert(!attributes.attrIsDir);
      assert(attributes.attrIsFile);

  Examples:
  getAttributes with a directory

      import std.exception : assertThrown;

      auto dir = deleteme ~ "dir";
      scope(exit) dir.rmdir;

      assert(!dir.exists);
      assertThrown!FileException(dir.getAttributes);

      dir.mkdir;
      auto attributes = dir.getAttributes;
      assert(attributes.attrIsDir);
      assert(!attributes.attrIsFile);

uint `getLinkAttributes`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
uint `getLinkAttributes`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  If the given file is a symbolic link, then this returns the attributes of the symbolic link itself rather than file that it points to. If the given file is not a symbolic link, then this function returns the same result as getAttributes.
  On Windows, getLinkAttributes is identical to getAttributes. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links.
  Parameters:

  R `name` | The file to get the symbolic link attributes of.

  Returns:
  the attributes
  Throws:
  FileException on error.
  Examples:

      import std.exception : assertThrown;

      auto source = deleteme ~ "source";
      auto target = deleteme ~ "target";

      assert(!source.exists);
      assertThrown!FileException(source.getLinkAttributes);

      // symlinking isn't available on Windows
      version (Posix)
      {
          scope(exit) source.remove, target.remove;

          target.write("target");
          target.symlink(source);
          writeln(source.readText); // "target"
          assert(source.isSymlink);
          assert(source.getLinkAttributes.attrIsSymlink);
      }

  Examples:
  if the file is no symlink, getLinkAttributes behaves like getAttributes

      import std.exception : assertThrown;

      auto f = deleteme ~ "file";
      scope(exit) f.remove;

      assert(!f.exists);
      assertThrown!FileException(f.getLinkAttributes);

      f.write(".");
      auto attributes = f.getLinkAttributes;
      assert(!attributes.attrIsDir);
      assert(attributes.attrIsFile);

  Examples:
  if the file is no symlink, getLinkAttributes behaves like getAttributes

      import std.exception : assertThrown;

      auto dir = deleteme ~ "dir";
      scope(exit) dir.rmdir;

      assert(!dir.exists);
      assertThrown!FileException(dir.getLinkAttributes);

      dir.mkdir;
      auto attributes = dir.getLinkAttributes;
      assert(attributes.attrIsDir);
      assert(!attributes.attrIsFile);

void `setAttributes`(R)(R `name`, uint `attributes`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
void `setAttributes`(R)(auto ref R `name`, uint `attributes`)
if (isConvertibleToString!R);
  Set the attributes of the given file.
  For example, a programmatic equivalent of Unix's chmod +x `name` to make a file executable is `name`.`setAttributes`(`name`.getAttributes | octal!700).
  Parameters:

  R `name` | the file name
  uint `attributes` | the attributes to set the file to

  Throws:
  FileException if the given file does not exist.
  Examples:
  setAttributes with a file

      import std.exception : assertThrown;
      import std.conv : octal;

      auto f = deleteme ~ "file";
      version (Posix)
      {
          scope(exit) f.remove;

          assert(!f.exists);
          assertThrown!FileException(f.setAttributes(octal!777));

          f.write(".");
          auto attributes = f.getAttributes;
          assert(!attributes.attrIsDir);
          assert(attributes.attrIsFile);

          f.setAttributes(octal!777);
          attributes = f.getAttributes;

          writeln((attributes & 1023)); // octal!777
      }

  Examples:
  setAttributes with a directory

      import std.exception : assertThrown;
      import std.conv : octal;

      auto dir = deleteme ~ "dir";
      version (Posix)
      {
          scope(exit) dir.rmdir;

          assert(!dir.exists);
          assertThrown!FileException(dir.setAttributes(octal!777));

          dir.mkdir;
          auto attributes = dir.getAttributes;
          assert(attributes.attrIsDir);
          assert(!attributes.attrIsFile);

          dir.setAttributes(octal!777);
          attributes = dir.getAttributes;

          writeln((attributes & 1023)); // octal!777
      }

@property bool `isDir`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
@property bool `isDir`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  Returns whether the given file is a directory.
  Parameters:

  R `name` | The path to the file.

  Returns:
  true if name specifies a directory
  Throws:
  FileException if the given file does not exist.
  Examples:

      import std.exception : assertThrown;

      auto dir = deleteme ~ "dir";
      auto f = deleteme ~ "f";
      scope(exit) dir.rmdir, f.remove;

      assert(!dir.exists);
      assertThrown!FileException(dir.isDir);

      dir.mkdir;
      assert(dir.isDir);

      f.write(".");
      assert(!f.isDir);

pure nothrow @nogc @safe bool `attrIsDir`(uint `attributes`);
  Returns whether the given file attributes are for a directory.
  Parameters:

  uint `attributes` | The file attributes.

  Returns:
  true if attributes specifies a directory
  Examples:

      import std.exception : assertThrown;

      auto dir = deleteme ~ "dir";
      auto f = deleteme ~ "f";
      scope(exit) dir.rmdir, f.remove;

      assert(!dir.exists);
      assertThrown!FileException(dir.getAttributes.attrIsDir);

      dir.mkdir;
      assert(dir.isDir);
      assert(dir.getAttributes.attrIsDir);

      f.write(".");
      assert(!f.isDir);
      assert(!f.getAttributes.attrIsDir);

@property bool `isFile`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
@property bool `isFile`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  Returns whether the given file (or directory) is a file.
  On Windows, if a file is not a directory, then it's a file. So, either `isFile` or isDir will return true for any given file.
  On POSIX systems, if `isFile` is true, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for both `isFile` and isDir to be false for a particular file (in which case, it's a special file). You can use getAttributes to get the attributes to figure out what type of special it is, or you can use DirEntry to get at its statBuf, which is the result from stat. In either case, see the man page for stat for more information.
  Parameters:

  R `name` | The path to the file.

  Returns:
  true if name specifies a file
  Throws:
  FileException if the given file does not exist.
  Examples:

      import std.exception : assertThrown;

      auto dir = deleteme ~ "dir";
      auto f = deleteme ~ "f";
      scope(exit) dir.rmdir, f.remove;

      dir.mkdir;
      assert(!dir.isFile);

      assert(!f.exists);
      assertThrown!FileException(f.isFile);

      f.write(".");
      assert(f.isFile);

pure nothrow @nogc @safe bool `attrIsFile`(uint `attributes`);
  Returns whether the given file attributes are for a file.
  On Windows, if a file is not a directory, it's a file. So, either `attrIsFile` or attrIsDir will return true for the attributes of any given file.
  On POSIX systems, if `attrIsFile` is true, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for both `attrIsFile` and attrIsDir to be false for a particular file (in which case, it's a special file). If a file is a special file, you can use the attributes to check what type of special file it is (see the man page for stat for more information).
  Parameters:

  uint `attributes` | The file attributes.

  Returns:
  true if the given file attributes are for a file

  Example

      assert(attrIsFile(getAttributes("/etc/fonts/fonts.conf")));
      assert(attrIsFile(getLinkAttributes("/etc/fonts/fonts.conf")));

  Examples:

      import std.exception : assertThrown;

      auto dir = deleteme ~ "dir";
      auto f = deleteme ~ "f";
      scope(exit) dir.rmdir, f.remove;

      dir.mkdir;
      assert(!dir.isFile);
      assert(!dir.getAttributes.attrIsFile);

      assert(!f.exists);
      assertThrown!FileException(f.getAttributes.attrIsFile);

      f.write(".");
      assert(f.isFile);
      assert(f.getAttributes.attrIsFile);

@property bool `isSymlink`(R)(R `name`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
@property bool `isSymlink`(R)(auto ref R `name`)
if (isConvertibleToString!R);
  Returns whether the given file is a symbolic link.
  On Windows, returns true when the file is either a symbolic link or a junction point.
  Parameters:

  R `name` | The path to the file.

  Returns:
  true if name is a symbolic link
  Throws:
  FileException if the given file does not exist.
  Examples:

      import std.exception : assertThrown;

      auto source = deleteme ~ "source";
      auto target = deleteme ~ "target";

      assert(!source.exists);
      assertThrown!FileException(source.isSymlink);

      // symlinking isn't available on Windows
      version (Posix)
      {
          scope(exit) source.remove, target.remove;

          target.write("target");
          target.symlink(source);
          writeln(source.readText); // "target"
          assert(source.isSymlink);
          assert(source.getLinkAttributes.attrIsSymlink);
      }

pure nothrow @nogc @safe bool `attrIsSymlink`(uint `attributes`);
  Returns whether the given file attributes are for a symbolic link.
  On Windows, return true when the file is either a symbolic link or a junction point.
  Parameters:

  uint `attributes` | The file attributes.

  Returns:
  true if attributes are for a symbolic link

  Example

      core.sys.posix.unistd.symlink("/etc/fonts/fonts.conf", "/tmp/alink");

      assert(!getAttributes("/tmp/alink").isSymlink);
      assert(getLinkAttributes("/tmp/alink").isSymlink);

  Examples:

      import std.exception : assertThrown;

      auto source = deleteme ~ "source";
      auto target = deleteme ~ "target";

      assert(!source.exists);
      assertThrown!FileException(source.getLinkAttributes.attrIsSymlink);

      // symlinking isn't available on Windows
      version (Posix)
      {
          scope(exit) source.remove, target.remove;

          target.write("target");
          target.symlink(source);
          writeln(source.readText); // "target"
          assert(source.isSymlink);
          assert(source.getLinkAttributes.attrIsSymlink);
      }

void `chdir`(R)(R `pathname`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
void `chdir`(R)(auto ref R `pathname`)
if (isConvertibleToString!R);
  Change directory to `pathname`. Equivalent to cd on Windows and POSIX.
  Parameters:

  R `pathname` | the directory to step into

  Throws:
  FileException on error.
  Examples:

      import std.algorithm.comparison : equal;
      import std.algorithm.sorting : sort;
      import std.array : array;
      import std.path : buildPath;

      auto cwd = getcwd;
      auto dir = deleteme ~ "dir";
      dir.mkdir;
      scope(exit) cwd.chdir, dir.rmdirRecurse;

      dir.buildPath("a").write(".");
      dir.chdir; // step into dir
      "b".write(".");
      assert(dirEntries(".", SpanMode.shallow).array.sort.equal(
          [".".buildPath("a"), ".".buildPath("b")]
      ));

void `mkdir`(R)(R `pathname`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
void `mkdir`(R)(auto ref R `pathname`)
if (isConvertibleToString!R);
  Make a new directory `pathname`.
  Parameters:

  R `pathname` | the path of the directory to make

  Throws:
  FileException on POSIX or WindowsException on Windows if an error occured.
  Examples:

      import std.file : mkdir;

      auto dir = deleteme ~ "dir";
      scope(exit) dir.rmdir;

      dir.mkdir;
      assert(dir.exists);

  Examples:

      import std.exception : assertThrown;
      assertThrown("a/b/c/d/e".mkdir);

@safe void `mkdirRecurse`(scope const(char)[] `pathname`);
  Make directory and all parent directories as needed.
  Does nothing if the directory specified by `pathname` already exists.
  Parameters:

  const(char)[] `pathname` | the full path of the directory to create

  Throws:
  FileException on error.
  Examples:

      import std.path : buildPath;

      auto dir = deleteme ~ "dir";
      scope(exit) dir.rmdirRecurse;

      dir.mkdir;
      assert(dir.exists);
      dir.mkdirRecurse; // does nothing

      // creates all parent directories as needed
      auto nested = dir.buildPath("a", "b", "c");
      nested.mkdirRecurse;
      assert(nested.exists);

  Examples:

      import std.exception : assertThrown;

      scope(exit) deleteme.remove;
      deleteme.write("a");

      // cannot make directory as it's already a file
      assertThrown!FileException(deleteme.mkdirRecurse);

void `rmdir`(R)(R `pathname`)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);
void `rmdir`(R)(auto ref R `pathname`)
if (isConvertibleToString!R);
  Remove directory `pathname`.
  Parameters:

  R `pathname` | Range or string specifying the directory name

  Throws:
  FileException on error.
  Examples:

      auto dir = deleteme ~ "dir";

      dir.mkdir;
      assert(dir.exists);
      dir.rmdir;
      assert(!dir.exists);

void `symlink`(RO, RL)(RO `original`, RL `link`)
if ((isSomeFiniteCharInputRange!RO || isConvertibleToString!RO) && (isSomeFiniteCharInputRange!RL || isConvertibleToString!RL));
  This function is POSIX-Only.
  Creates a symbolic link (symlink).
  Parameters:

  RO `original` | The file that is being linked. This is the target path that's stored in the symlink. A relative path is relative to the created symlink.
  RL `link` | The symlink to create. A relative path is relative to the current working directory.

  Throws:
  FileException on error (which includes if the symlink already exists).
string `readLink`(R)(R `link`)
if (isSomeFiniteCharInputRange!R || isConvertibleToString!R);
  This function is POSIX-Only.
  Returns the path to the file pointed to by a symlink. Note that the path could be either relative or absolute depending on the symlink. If the path is relative, it's relative to the symlink, not the current working directory.
  Throws:
  FileException on error.
@trusted string `getcwd`();
  Get the current working directory.
  Throws:
  FileException on error.
  Examples:

      auto s = getcwd();
      assert(s.length);

@trusted string `thisExePath`();
  Returns the full path of the current executable.
  Returns:
  The path of the executable as a string.
  Throws:
  Exception
  Examples:

      import std.path : isAbsolute;
      auto path = thisExePath();

      assert(path.exists);
      assert(path.isAbsolute);
      assert(path.isFile);

struct `DirEntry`;
  Info on a file, similar to what you'd get from stat on a POSIX system.
  @safe this(return scope string `path`);
    Constructs a DirEntry for the given file (or directory).
    Parameters:

    string `path` | The file (or directory) to get a DirEntry for.

    Throws:
    FileException if the file does not exist.
  const @property @safe string `name`() return;
    Returns the path to the file represented by this DirEntry.

    Example

        auto de1 = DirEntry("/etc/fonts/fonts.conf");
        assert(de1.name == "/etc/fonts/fonts.conf");

        auto de2 = DirEntry("/usr/share/include");
        assert(de2.name == "/usr/share/include");

  @property @safe bool `isDir`();
    Returns whether the file represented by this DirEntry is a directory.

    Example

        auto de1 = DirEntry("/etc/fonts/fonts.conf");
        assert(!de1.isDir);

        auto de2 = DirEntry("/usr/share/include");
        assert(de2.isDir);

  @property @safe bool `isFile`();
    Returns whether the file represented by this DirEntry is a file.
    On Windows, if a file is not a directory, then it's a file. So, either `isFile` or isDir will return true.
    On POSIX systems, if `isFile` is true, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for both `isFile` and isDir to be false for a particular file (in which case, it's a special file). You can use attributes or statBuf to get more information about a special file (see the stat man page for more details).

    Example

        auto de1 = DirEntry("/etc/fonts/fonts.conf");
        assert(de1.isFile);

        auto de2 = DirEntry("/usr/share/include");
        assert(!de2.isFile);

  @property @safe bool `isSymlink`();
    Returns whether the file represented by this DirEntry is a symbolic link.
    On Windows, return true when the file is either a symbolic link or a junction point.
  @property @safe ulong `size`();
    Returns the size of the file represented by this DirEntry in bytes.
  const @property @safe SysTime `timeCreated`();
    This function is Windows-Only.
    Returns the creation time of the file represented by this DirEntry.
  @property @safe SysTime `timeLastAccessed`();
    Returns the time that the file represented by this DirEntry was last accessed.
    Note that many file systems do not update the access time for files (generally for performance reasons), so there's a good chance that `timeLastAccessed` will return the same value as timeLastModified.
  @property @safe SysTime `timeLastModified`();
    Returns the time that the file represented by this DirEntry was last modified.
  const @property @safe SysTime `timeStatusChanged`();
    This function is POSIX-Only.
    Returns the time that the file represented by this DirEntry was last changed (not only in contents, but also in permissions or ownership).
  @property @safe uint `attributes`();
    Returns the attributes of the file represented by this DirEntry.
    Note that the file attributes on Windows and POSIX systems are completely different. On, Windows, they're what is returned by GetFileAttributes GetFileAttributes Whereas, an POSIX systems, they're the st_mode value which is part of the stat struct gotten by calling stat.
    On POSIX systems, if the file represented by this DirEntry is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link.
  @property @safe uint `linkAttributes`();
    On POSIX systems, if the file represented by this DirEntry is a symbolic link, then `linkAttributes` are the attributes of the symbolic link itself. Otherwise, `linkAttributes` is identical to attributes.
    On Windows, `linkAttributes` is identical to attributes. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links.
  @property @safe stat_t `statBuf`();
    This function is POSIX-Only.
    The stat struct gotten from calling stat.
PreserveAttributes `preserveAttributesDefault`;
  Defaults to Yes.preserveAttributes on Windows, and the opposite on all other platforms.
void `copy`(RF, RT)(RF `from`, RT `to`, PreserveAttributes `preserve` = preserveAttributesDefault)
if (isSomeFiniteCharInputRange!RF && !isConvertibleToString!RF && isSomeFiniteCharInputRange!RT && !isConvertibleToString!RT);
void `copy`(RF, RT)(auto ref RF `from`, auto ref RT `to`, PreserveAttributes `preserve` = preserveAttributesDefault)
if (isConvertibleToString!RF || isConvertibleToString!RT);
  Copy file `from` to file `to`. File timestamps are preserved. File attributes are preserved, if `preserve` equals Yes.preserveAttributes. On Windows only Yes.preserveAttributes (the default on Windows) is supported. If the target file exists, it is overwritten.
  Parameters:

  RF `from` | string or range of characters representing the existing file name
  RT `to` | string or range of characters representing the target file name
  PreserveAttributes `preserve` | whether to preserve the file attributes

  Throws:
  FileException on error.
  Examples:

      auto source = deleteme ~ "source";
      auto target = deleteme ~ "target";
      auto targetNonExistent = deleteme ~ "target2";

      scope(exit) source.remove, target.remove, targetNonExistent.remove;

      source.write("source");
      target.write("target");

      writeln(target.readText); // "target"

      source.copy(target);
      writeln(target.readText); // "source"

      source.copy(targetNonExistent);
      writeln(targetNonExistent.readText); // "source"

@safe void `rmdirRecurse`(scope const(char)[] `pathname`);
@safe void `rmdirRecurse`(ref scope DirEntry `de`);
@safe void `rmdirRecurse`(scope DirEntry `de`);
  Remove directory and all of its content and subdirectories, recursively.
  Parameters:

  const(char)[] `pathname` | the path of the directory to completely remove
  DirEntry `de` | The DirEntry to remove

  Throws:
  FileException if there is an error (including if the given file is not a directory).
  Examples:

      import std.path : buildPath;

      auto dir = deleteme.buildPath("a", "b", "c");

      dir.mkdirRecurse;
      assert(dir.exists);

      deleteme.rmdirRecurse;
      assert(!dir.exists);
      assert(!deleteme.exists);

enum `SpanMode`: int;
  Dictates directory spanning policy for dirEntries (see below).
  Examples:

      import std.algorithm.comparison : equal;
      import std.algorithm.iteration : map;
      import std.algorithm.sorting : sort;
      import std.array : array;
      import std.path : buildPath, relativePath;

      auto root = deleteme ~ "root";
      scope(exit) root.rmdirRecurse;
      root.mkdir;

      root.buildPath("animals").mkdir;
      root.buildPath("animals", "cat").mkdir;

      alias removeRoot = (return scope e) => e.relativePath(root);

      assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
          [buildPath("animals", "cat"), "animals"]));

      assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
          ["animals", buildPath("animals", "cat")]));

      root.buildPath("plants").mkdir;

      assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
          ["animals", "plants"]));

  `shallow`
    Only spans one directory.
  `depth`
    Spans the directory in depth-first post-order, i.e. the content of any subdirectory is spanned before that subdirectory itself. Useful e.g. when recursively deleting files.
  `breadth`
    Spans the directory in depth-first pre-order, i.e. the content of any subdirectory is spanned right after that subdirectory itself.
    Note that SpanMode.`breadth` will not result in all directory members occurring before any subdirectory members, i.e. it is not true breadth-first traversal.
auto `dirEntries`(bool useDIP1000 = dip1000Enabled)(string `path`, SpanMode `mode`, bool `followSymlink` = true);
auto `dirEntries`(bool useDIP1000 = dip1000Enabled)(string `path`, string `pattern`, SpanMode `mode`, bool `followSymlink` = true);
  Returns an input range of DirEntry that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of type string if only the name is needed, or DirEntry if additional details are needed. The span mode dictates how the directory is traversed. The name of each iterated directory entry contains the absolute or relative path (depending on pathname).

  Note The order of returned directory entries is as it is provided by the operating system / filesystem, and may not follow any particular sorting.

  Parameters:

  useDIP1000 | used to instantiate this function separately for code with and without -preview=dip1000 compiler switch, because it affects the ABI of this function. Set automatically - don't touch.
  string `path` | The directory to iterate over. If empty, the current directory will be iterated.
  string `pattern` | Optional string with wildcards, such as "*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under std.path.globMatch.
  SpanMode `mode` | Whether the directory's sub-directories should be iterated in depth-first post-order (depth), depth-first pre-order (breadth), or not at all (shallow).
  bool `followSymlink` | Whether symbolic links which point to directories should be treated as directories and their contents iterated over.

  Returns:
  An input range of DirEntry.
  Throws:
  FileException if the directory does not exist.

  Example

      // Iterate a directory in depth
      foreach (string name; dirEntries("destroy/me", SpanMode.depth))
      {
          remove(name);
      }

      // Iterate the current directory in breadth
      foreach (string name; dirEntries("", SpanMode.breadth))
      {
          writeln(name);
      }

      // Iterate a directory and get detailed info about it
      foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
      {
          writeln(e.name, "\t", e.size);
      }

      // Iterate over all *.d files in current directory and all its subdirectories
      auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
      foreach (d; dFiles)
          writeln(d.name);

      // Hook it up with std.parallelism to compile them all in parallel:
      foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
      {
          string cmd = "dmd -c "  ~ d.name;
          writeln(cmd);
          std.process.executeShell(cmd);
      }

      // Iterate over all D source files in current directory and all its
      // subdirectories
      auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
      foreach (d; dFiles)
          writeln(d.name);

  Examples:
  Duplicate functionality of D1's std.file.listdir():

      string[] listdir(string pathname)
      {
          import std.algorithm;
          import std.array;
          import std.file;
          import std.path;

          return std.file.dirEntries(pathname, SpanMode.shallow)
              .filter!(a => a.isFile)
              .map!((return a) => std.path.baseName(a.name))
              .array;
      }

      // Can be safe only with -preview=dip1000
      @safe void main(string[] args)
      {
          import std.stdio;

          string[] files = listdir(args[1]);
          writefln("%s", files);
      }

Select!(Types.length == 1, Types[0][], Tuple!Types[]) `slurp`(Types...)(string `filename`, scope const(char)[] `format`);
  Reads a file line by line and parses the line into a single value or a std.typecons.Tuple of values depending on the length of Types. The lines are parsed using the specified format string. The format string is passed to std.format.formattedRead, and therefore must conform to the format string specification outlined in std.format.
  Parameters:

  Types | the types that each of the elements in the line should be returned as
  string `filename` | the name of the file to read
  const(char)[] `format` | the format string to use when reading

  Returns:
  If only one type is passed, then an array of that type. Otherwise, an array of std.typecons.Tuples.
  Throws:
  Exception if the format string is malformed. Also, throws Exception if any of the lines in the file are not fully consumed by the call to std.format.formattedRead. Meaning that no empty lines or lines with extra characters are allowed.
  Examples:

      import std.typecons : tuple;

      scope(exit)
      {
          assert(exists(deleteme));
          remove(deleteme);
      }

      write(deleteme, "12 12.25\n345 1.125"); // deleteme is the name of a temporary file

      // Load file; each line is an int followed by comma, whitespace and a
      // double.
      auto a = slurp!(int, double)(deleteme, "%s %s");
      writeln(a.length); // 2
      writeln(a[0]); // tuple(12, 12.25)
      writeln(a[1]); // tuple(345, 1.125)

@trusted string `tempDir`();
  Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:
  1. The directory given by the TMPDIR environment variable.
  2. The directory given by the TEMP environment variable.
  3. The directory given by the TMP environment variable.
  4. /tmp/
  5. /var/tmp/
  6. /usr/tmp/
  On all platforms, `tempDir` returns the current working directory on failure.
  The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.
  The POSIX `tempDir` algorithm is inspired by Python's tempfile.tempdir.
  Returns:
  On Windows, this function returns the result of calling the Windows API function GetTempPath.
  On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:
  1. The directory given by the TMPDIR environment variable.
  2. The directory given by the TEMP environment variable.
  3. The directory given by the TMP environment variable.
  4. /tmp
  5. /var/tmp
  6. /usr/tmp
  On all platforms, `tempDir` returns "." on failure, representing the current working directory.
  Examples:

      import std.ascii : letters;
      import std.conv : to;
      import std.path : buildPath;
      import std.random : randomSample;
      import std.utf : byCodeUnit;

      // random id with 20 letters
      auto id = letters.byCodeUnit.randomSample(20).to!string;
      auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
      scope(exit) myFile.remove;

      myFile.write("hello");
      writeln(myFile.readText); // "hello"

@safe ulong `getAvailableDiskSpace`(scope const(char)[] `path`);
  Returns the available disk space based on a given path. On Windows, `path` must be a directory; on POSIX systems, it can be a file or directory.
  Parameters:

  const(char)[] `path` | on Windows, it must be a directory; on POSIX it can be a file or directory

  Returns:
  Available space in bytes
  Throws:
  FileException in case of failure
  Examples:

      import std.exception : assertThrown;

      auto space = getAvailableDiskSpace(".");
      assert(space > 0);

      assertThrown!FileException(getAvailableDiskSpace("ThisFileDoesNotExist123123"));

Copyright © 1999-2023 by the D Language Foundation | Page generated by Ddoc on Sun Jan 1 02:20:52 2023