movefile() on the same filesystem does not make a copy of the original file. You can see this by examining the ownerships and permissions and timestamps: they stay the same as long as the filesystem stays the same. (Whether they stay the same when moved to a different filesystem is dependent upon the operating system and file systems involved.)
But that is a detail. The difficulty is that most filesystems for MS Windows either are always case-insensitive or else are typically configured to be case-insensitive. For those filesystems MS Windows detects that the filename is not changing as far as the filesystem is concerned and it refuses the movefile()
The work-around is to movefile() to a name that is not in use, and then movefile() to the new name.
src = 'test.txt';
dest = 'Test.txt';
if isempty(src) || isempty(dest) || ~ischar(src) || ~ischar(dest)
error('source or destination are invalid');
end
if strcmp(src, dest)
warning('source and destination are the same, nothing done');
elseif ispc() && strcmpi(src, dest)
srcdir = fileparts(src);
if isempty(srcdir); srcdir = pwd(); end
tname = tempname(srcdir);
movefile(src, tname);
movefile(tname, dest);
else
movefile(src, dest);
end
The above code is not fool-proof. In particular it does not check for the possibility that the src and dest refer to the same file through different paths. For example './test.txt' would be considered different than 'Test.txt' in this code even though they refer to the same file. The code also does not check whether the src is a directory, which is invalid for movefile(). (A destination which is a directory is valid for movefile())
Best Answer