Temporary Files And Directories in Pascal

Our program demonstrates how to work with temporary files and directories. Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

program TempFilesAndDirs;

uses
  SysUtils;

procedure Check(E: Exception);
begin
  if Assigned(E) then
    raise E;
end;

var
  TempFile: TextFile;
  TempFileName, TempDirName, FullFileName: string;
  E: Exception;

begin
  try
    // Create a temporary file
    TempFileName := GetTempFileName;
    AssignFile(TempFile, TempFileName);
    Rewrite(TempFile);
    
    // Display the name of the temporary file
    WriteLn('Temp file name: ', TempFileName);
    
    // Write some data to the file
    Write(TempFile, #1#2#3#4);
    CloseFile(TempFile);
    
    // Create a temporary directory
    TempDirName := GetTempDir + 'sampledir' + IntToStr(Random(1000000));
    ForceDirectories(TempDirName);
    WriteLn('Temp dir name: ', TempDirName);
    
    // Create a file in the temporary directory
    FullFileName := TempDirName + PathDelim + 'file1';
    AssignFile(TempFile, FullFileName);
    Rewrite(TempFile);
    Write(TempFile, #1#2);
    CloseFile(TempFile);
  except
    on E: Exception do
      Check(E);
  end;
  
  // Clean up
  DeleteFile(TempFileName);
  DeleteDirectory(TempDirName, True);
end.

In this Pascal program:

  1. We use GetTempFileName to create a temporary file. This function automatically generates a unique filename in the system’s temporary directory.

  2. We display the name of the temporary file using WriteLn.

  3. We write some data to the file using Write.

  4. To create a temporary directory, we use GetTempDir to get the system’s temporary directory, then append a unique name. We use ForceDirectories to create this directory.

  5. We create a file within the temporary directory by joining the directory name with a file name using PathDelim.

  6. Finally, we clean up by deleting the temporary file and directory. DeleteFile removes the file, and DeleteDirectory removes the directory and its contents.

Note that Pascal doesn’t have built-in functions exactly equivalent to Go’s os.CreateTemp or os.MkdirTemp. We’ve used similar concepts to achieve the same result.

To run this program, save it as TempFilesAndDirs.pas and compile it with a Pascal compiler. The output will show the paths of the temporary file and directory created.

$ fpc TempFilesAndDirs.pas
$ ./TempFilesAndDirs
Temp file name: /tmp/tempfile123456
Temp dir name: /tmp/sampledir789012

Remember that the actual file and directory names will be different each time you run the program, as they are generated uniquely.