フィルターのクリア

Check files in current folder (MatLab path)

65 ビュー (過去 30 日間)
Lucas
Lucas 2012 年 10 月 2 日
I'm running into a slight problem, I'm trying to generate unique names for some files and I need to check if that name exists in the current folder. Some files are named like:
2Hello
3Hello
Since MatLab can’t have numbers at the beginning of file names, I remove that and get ‘Hello’ and I check if that files exists using something like:
exist(Hello, file);
If that returns zero I make that the file name. So when I do that with the second name, I remove the 3 and I also get ‘Hello’. When I check it with exists it returns 4, so I append a number to the end and get ‘Hello1’ and check that. This works the way that I want it to until I delete the files and try again. The next time I run it on these 2 files I get ‘Hello2’ and ‘Hello3’ back.
I have 2 issues with this. The first is I deleted the files so those names shouldn’t exist anywhere on the MatLab path, and the second is that this folder isn’t even on the MatLab path. I don’t have the current folder that I’m working in on the MatLab ‘SetPath’. If I restart MatLab and I run exists on ‘Hello’ through ‘Hello3’ I get 0’s every time, so does exists check MatLab memory and not the MatLab path like it says, if so I think the file should be updated to say that.
So finally to my question, does MatLab have an alternative to exists? One that just checks the current folder that MatLab is pointing too? I don’t care if it conflicts with another name in a different folder, just as long as it’s unique to that folder. Thanks!

採用された回答

Jan
Jan 2012 年 10 月 2 日
編集済み: Jan 2012 年 10 月 2 日
You should use EXIST with an absolute path for files:
currentFolder = cd;
fileExisting = (exist(fullfile(currentFolder, 'File'), 'file') == 2);
Using EXIST without absolute path, Matlab searchs all folders in its PATH.
Now EXIST still considers other object like folders, Java libs and DLLs, e.g. fullfile(currentFolder, 'File.dll'). The comparison with 2 cares for these exceptions also.
I admit, EXIST is too smart for checking for the existence of files. I'm using a faster and more robust Mex file for this job.
  1 件のコメント
Daniel Shub
Daniel Shub 2012 年 10 月 2 日
I think exist is often to smart to really be useful.

サインインしてコメントする。

その他の回答 (1 件)

Daniel Shub
Daniel Shub 2012 年 10 月 2 日
You can use dir. Something like
x = dir;
any(strcmp(fname, {x(~[x.isdir]).name}));
  1 件のコメント
Daniel Shub
Daniel Shub 2012 年 10 月 2 日
Yes, it returns . and .., but they are directories (at least in Linux) so left out of the comparison. As for striping the extension you can process each element of {x(~[x.isdir]).name} with fileparts to strip the extension.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by