copyfile

Copies a file or a folder.

Category: Programming > Files and Folders

Syntax

copyfile(source, destination)

Copies source to destination.

[status, message, messageid] = copyfile(___)

Returns a status flag and a message describing the outcome.

Description

When source is a file and destination is an existing folder, the file keeps its name inside that folder; when destination is a new name, the copy gets that name. A wildcard source copies every match, and the destination should then be a folder. A folder source is copied together with its contents.

Without output arguments a failure is an error; with them the outcome is reported in status and message.

Input arguments

source
File, folder or wildcard pattern such as '*.txt'.
destination
Target file name or existing folder.

Output arguments

status
true when the copy succeeded.
message
Text describing the problem, empty on success.
messageid
Message identifier, empty on success.

Example

Copying to a new name and into a folder

writelines(["alpha"; "beta"], 'a.txt');
[ok, msg] = copyfile('a.txt', 'b.txt')
mkdir backup
copyfile('a.txt', 'backup');
isfile('backup/a.txt')
Output
ok = logical
   1
msg = 0×0 empty char array
ans = logical
   1

Notes

When the source matches nothing, MatLivre raises the error No matching files were found. even if output arguments were requested, whereas MATLAB returns a false status.

See also

movefile delete mkdir dir isfile