Skip to content

Commit 7bd919d

Browse files
authored
Add z_tempfile:copy/1 and extra docs (#109)
1 parent 8a5e7c8 commit 7bd919d

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

src/z_tempfile.erl

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
11
%% @author Marc Worrell <[email protected]>
2-
%% @copyright 2011-2020 Marc Worrell
3-
%% @doc Simple temporary file handling, deletes the file when the calling process stops or crashes.
2+
%% @copyright 2011-2025 Marc Worrell
3+
%% @doc Simple temporary file handling, deletes the file when the calling process
4+
%% stops or crashes. If a file is created then a watchdog process is started to
5+
%% monitor the calling process. If the calling process is stopped or crashes then
6+
%% the file is deleted.
7+
%%
8+
%% Periodically call cleanup/0 to delete temporary files older than 24 hours.
9+
%%
10+
%% Temporary files are created in the directory specified by the TMP or TEMP environment
11+
%% variable, or /tmp if none is set.
12+
%% @end
413

5-
%% Copyright 2011-2020 Marc Worrell
14+
%% Copyright 2011-2025 Marc Worrell
615
%%
716
%% Licensed under the Apache License, Version 2.0 (the "License");
817
%% you may not use this file except in compliance with the License.
@@ -22,6 +31,7 @@
2231
-export([
2332
new/0,
2433
new/1,
34+
copy/1,
2535

2636
monitored_new/0,
2737
monitored_new/1,
@@ -61,6 +71,20 @@ new(Extension) ->
6171
{ok, {_Pid, Filename}} = monitored_new(Extension),
6272
Filename.
6373

74+
%% @doc Copy a file to a new tempfile, start a monitoring process to clean it up after use.
75+
-spec copy(File) -> {ok, NewFile} | {error, Reason} when
76+
File :: file:filename_all(),
77+
NewFile :: file:filename_all(),
78+
Reason :: term().
79+
copy(File) ->
80+
{ok, {_Pid, NewFile}} = monitored_new(),
81+
case file:copy(File, NewFile) of
82+
{ok, _BytesCopied} ->
83+
{ok, NewFile};
84+
{error, _} = Error ->
85+
Error
86+
end.
87+
6488
%% @doc Like new/0 but also return the Pid of the monitoring process.
6589
-spec monitored_new() -> {ok, {pid(), file:filename_all()}}.
6690
monitored_new() ->

0 commit comments

Comments
 (0)