Sign in Join
Wiki copytemporary

Locating the macOS tmp directory

(macOS only)

Overview

To locate the current user's temporary directory in macOS you should use the native macOS Foundation function NSTemporaryDirectory(). This directory is unique for each user, the user is guaranteed to have write permissions to it, and it is in a hashed location which is not predictable in advance so that it is safe from security issues associated with predictable locations. It is also guaranteed to work when your application has been sandboxed.

You should be aware that this directory is cleaned out automatically every 3 days but otherwise persists between application launches and reboots.

Determining where to store files

Storing temporary files

How to locate the user's unique temporary directory, display it and write a temporary file to it is demonstrated by the code below:

pascal
...
{$modeswitch objectivec1} 

interface

Uses
  ...
  CocoaAll;
...

procedure TmpFile;
var
  tmpFile: TextFile;
  filePath: String;
begin
  ShowMessage(NSTemporaryDirectory.UTF8String);

  filePath := NSTemporaryDirectory.Utf8String + 'test.tmp';

  AssignFile(TmpFile, filePath);
  Try
    Rewrite(TmpFile);
    Writeln(TmpFile, 'This is my test tmp file.');
  Finally
    CloseFile(TmpFile);
  End;
end;

Why not use GetTempDir?

It should be noted that Free Pascal's GetTempDir function (from SysUtils) uses the value of the macOS TMPDIR environment variable to determine the path to where the current user's temporary files should be stored. This is a possible security issue because the TMPDIR environment variable is easily compromised.

See also


From the Free Pascal wiki, page "Locating the macOS tmp directory", as it stood on 2021-03-26 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .

Edited on wiki.freepascal.org by 2 people, 2019–2021

From the official wiki's backup of 26 May 2024: who edited this page there, and when. Edits made there after that date were not recorded, and the earlier versions are not shown here; the main page says why.

WhenWhoWhat changed
TrevNew page content for macOS :-
TrevFix template (minor)
TrevDetermining where to store files: Added TM note to tmp dir location (minor)
TrevStoring temporary files: Resolved compiler uninitialised var warning (minor)
FTurtleAdded template
TrevFixed page link (minor)
TrevDetermining where to store files: Expanded detail (minor)
TrevDetermining where to store files: content moved to template (minor)
TrevStoring temporary files: Updated code (minor)
TrevStoring temporary files: Updated code
TrevStoring temporary files: Code simplified at the suggestion of ChrisR
TrevSee also: New section

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.