MATLAB: Case-sensitive file move

caseMATLABmovefilerenaming

Is it possible to rename a file if the only difference between the old and new names is the case? A command such as
movefile('test.txt','Test.txt')
returns the error
Cannot copy or move a file or directory onto itself.
I'm making a GUI with the option to rename files, and while being able to do case-sensitive moves like that is not essential, it would certainly be nice.

Best Answer

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)
%MS Windows is usually case-insensitive so we need a work-around
%do not assume that the source is the current directory
srcdir = fileparts(src);
if isempty(srcdir); srcdir = pwd(); end %in case no directory spec was included
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())
Related Question