Check files in current folder (MatLab path)

92 views (last 30 days)
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!

Accepted Answer

Jan
Jan on 2 Oct 2012
Edited: Jan on 2 Oct 2012
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.

More Answers (1)

Daniel Shub
Daniel Shub on 2 Oct 2012
You can use dir. Something like
x = dir;
any(strcmp(fname, {x(~[x.isdir]).name}));
  1 Comment
Daniel Shub
Daniel Shub on 2 Oct 2012
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.

Sign in to comment.

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!