Check files in current folder (MatLab path)
37 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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!
0 comentarios
Respuesta aceptada
Jan
el 2 de Oct. de 2012
Editada: Jan
el 2 de Oct. de 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.
1 comentario
Más respuestas (1)
Daniel Shub
el 2 de Oct. de 2012
You can use dir. Something like
x = dir;
any(strcmp(fname, {x(~[x.isdir]).name}));
1 comentario
Daniel Shub
el 2 de Oct. de 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.
Ver también
Categorías
Más información sobre File Operations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!