making multiple copies of a file

40 visualizzazioni (ultimi 30 giorni)
Ram il 1 Set 2011
Risposto: Sam Apoola il 14 Feb 2019
I would like to make multiple copies of a file each of which will have a different name. example: source file: A.txt copies A1.txt, A2.txt... How can I use copyfile and be able to do this? Thanks for inputs

Risposta accettata

Walter Roberson
Walter Roberson il 1 Set 2011
copyfile() can only create one copy at a time, so you will need a loop (whether explicit or implicit)
One of numerous possible ways:
sourcefile = 'A.txt';
numcopies = 20;
[path, basename, ext] = fileparts(sourcefile);
filepattern = fullfile(path, [basename '%d.' ext]);
destnames = cellstr(num2str((1:numcopies).', filepattern);
cellfun(@(FID) copyfile(sourcefile, FID), destnames);
  4 Commenti
Walter Roberson
Walter Roberson il 1 Set 2011
Looks like I left off a close bracket:
destnames = cellstr(num2str((1:numcopies).', filepattern));

Accedi per commentare.

Più risposte (3)

Amith il 26 Dic 2012
will this work
  1 Commento
Walter Roberson
Walter Roberson il 26 Dic 2012
No, destnames here is a cell array of strings, so destnames(i) would be a 1 x 1 cellarray, rather than a string. If you used destnames{i} then that would be a string.
You would need to loop "i" over all of the output string possibilities. The cellfun() that I show is responsible for that.

Accedi per commentare.

Diana Krupnik
Diana Krupnik il 28 Gen 2019
This solution names the files by numbering them, would it be possible to instead change the names based on a table that contains string or text?

Sam Apoola
Sam Apoola il 14 Feb 2019
This worked for me
% loop for creating 100 copies
for i=1:n
jobname{i}= ['copy', num2str(i),'.txt'];


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by