Check files in current folder (MatLab path)

35 次查看(过去 30 天)
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
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 CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by