How can i change a filename.

6 views (last 30 days)
rahul Sarkar
rahul Sarkar on 10 Feb 2016
Commented: Walter Roberson on 10 Feb 2016
i am using this code to change a name of a file
clc;
clear all;
e=1;
for s=7:8 % Loop for total number of items
for t=0:9 % Loop for items in the gallery TBD =9
f1=['Sub3D_I_', int2str(e), '_', int2str(t), '.dat']
Newf1=['Sub3D_I_', int2str(e), '_', int2str(t), '.dat']
cd('D:\Folder where data is stored ')
fid = fopen(f1, 'r');
if fid<0
break
else
movefile(f1,Newf1)
e=e+1;
end
end
end
however i am getting this error ??? Error using ==> movefile The process cannot access the file because it is being used by another process.
Error in ==> NameChange1 at 19 movefile(f1,Newf1)
can anyone please help

Accepted Answer

Guillaume
Guillaume on 10 Feb 2016
Most (all?) operating systems won't let you rename / move a file if it's in use (meaning it's been opened). Since you open the file and never close it before trying to rename it, it is always going to fail.
Why are you opening the file before trying to move it? To check that it exists? If so, you should close the file before moving it but even that is not enough to guarantee that the move will be successful. You may have read permissions but not modify permissions, the file may have disappeared in between your test and the move, etc. In fact, the only way to know if the move will succeed is to try it. You can recover from a failed move by wrapping the move in a try ... catch statement. This is the only way to to perform a move safely.
Also, you don't need (and shouldn't) cd into the directory. Much better is to specify the full path of the files in the move. So:
e=1; %what a bad name for a variable. How about filecount instead?
folder = 'D:\somewhere\where\the\file\is';
for s=7:8 % Loop for total number of items
for t=0:9 % Loop for items in the gallery TBD =9
f1 = sprintf('Sub3D_I%d_%d.dat', e, t); %more readable in my opinion
Newf1 = sprintf('Sub3D_I_%d_%d.dat', e, t); %same
try
movefile(fullfile(folder, f1), fullfile(folder, Newf1));
e = e + 1;
catch
break;
end
end
  1 Comment
Walter Roberson
Walter Roberson on 10 Feb 2016
Unix operating systems allow you to move a file that is open. However, Unix operating systems do not allow you to move a file to itself, which is being done here because the f1 and Newf1 are the same.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!