Be Absolute about your Relative Path with GetFullPath
Jiro's pick this week is GetFullPath by Jan.
Jan is no stranger to good File Exchange entries. I've already highlighted two of his entries before (cryptAES and AutoWarnDlg). This one is a very handy utility for those working with files in different directories and needing an easy way to get absolute path names from relative or partial names. I'm a little embarrassed to say that I didn't see the pain I was having until I came across Jan's entry. In various MATLAB programs, I have used code that looked like this. I'm using fileparts to go up directories and fullfile to construct paths.
curDir = pwd mainDir = fileparts(fileparts(curDir)); % go up 2 directories imgFile1 = fullfile(mainDir, 'Internal', 'GoogleMap.png') % Check that the file exists assert(exist(imgFile1, 'file') == 2, 'File does not exist')
curDir = C:\MyStuff\Work\NoCopy\Blog\POTW\FullPath imgFile1 = C:\MyStuff\Work\NoCopy\Blog\Internal\GoogleMap.png
I can use relative path along with fullfile, but the result looks kind of messy:
imgFile2 = fullfile(curDir, '..', '..', 'Internal', 'GoogleMap.png') % Check that the file exists assert(exist(imgFile2, 'file') == 2, 'File does not exist');
imgFile2 = C:\MyStuff\Work\NoCopy\Blog\POTW\FullPath\..\..\Internal\GoogleMap.png
With Jan's GetFullPath, I get exactly what I want, with a simple, familiar syntax:
imgFile3 = GetFullPath('..\..\Internal\GoogleMap.png') % Check that the file exists assert(exist(imgFile3, 'file') == 2, 'File does not exist');
imgFile3 = C:\MyStuff\Work\NoCopy\Blog\Internal\GoogleMap.png
If you're familiar with some of Jan's entries, he has included a fast C-Mex version of the code (Windows-only), but for people like me who breathe MATLAB, the .m version is enough to evoke a smile. He also includes a unit test suite for his function, which is always a good practice.
Let us know what you think here or leave a comment for Jan.
コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。