Case-sensitive file move
4 ビュー (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
採用された回答
Walter Roberson
2016 年 1 月 11 日
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())
その他の回答 (1 件)
Vaibhav Awale
2016 年 1 月 11 日
Hi,
The command;
>> movefile('test.txt','Test.txt')
makes a copy of the original file and then removes the original file. Now both files are located in the same folder and Windows systems are not case sensitive with respect to file names. Hence MATLAB throws an error saying "Cannot copy or move a file or directory onto itself."
Regards,
Vaibhav Awale
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Search Path についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!