Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Loren on the Art of MATLAB

April 13th, 2007

Machine-Independent Filenames

When developing applications is MATLAB, I often find myself interacting with files, sometimes data, sometimes algorithms. In order to be sure I am operating with the correct file, for example for loading data, I want to use the full path. However, I also want to pass my program on to other users, and their path information might not match mine.

Contents

Recent Example at The MathWorks

Recently at The MathWorks, someone wanted to share some files with another person so they could discuss the content. To do so, the author provided code that looked like this. Here YEAR is a variable of class char.

   load(['T:\1-36U6NN\secprd',YEAR,'.txt'])

You might wonder what the problem with this is. Well, for one thing, the author works on a Windows platform, but the recipient frequently does not. So how could this code have been written differently?

The T:\ drive maps to a file server that is accessible from any of our networked computers. So one possibility is to write code something like this:

      baseLocationWin = 'T:\';
      baseLocationOther = '//home/tester';
      if ispc  % true for windows platforms
          baseLocation = baseLocationWin;
      else
          baseLocation = baseLocationOther;
      end
      path1 = '1-36U6NN';
      YEAR = '2001';
      fname = ['secprd' YEAR '.txt'];
      fullfname = fullfile(baseLocation, path1, fname);

On Windows, where I ran this code, here's the file name.

disp(fullfname)
T:\1-36U6NN\secprd2001.txt

The equivalent UNIX pathname would be

disp([baseLocationOther '/' path1, '/' fname])
//home/tester/1-36U6NN/secprd2001.txt

Reference Material

Here you'll see a list of some MATLAB functions that are useful in writing machine independent applications when it comes to referring to files.

Comments

Have you been in this situation? Do you have other techniques to help users write robust code for handling files? If so, please post here.


Get the MATLAB code

Published with MATLAB® 7.4

14 Responses to “Machine-Independent Filenames”

  1. Dan K replied on :

    Loren,
    Perhaps you can offer a more elegant solution to the problem which I have encountered (and kludged around). We have a company server (’Company’), which on my machine is mapped to drive Y. But I can’t always rely on other users mapping to the same drive. The only solution which I could establish was to call dos(’net use’) and parse the response to find the word ‘Company’, and then extract which drive letter it is mapped to. Any thoughts on a more elegant way to achieve this?

    Dan K

  2. hUser replied on :

    Why not use the UNC path rather then then drive. All of the matlab commands I am aware of can use it.

    I was able to get rid of many problems by always using the unc path.

  3. Dan K replied on :

    hUser,
    Thanks for the response. The problem as I understand it is that many of the commands don’t work with unc paths on a windows machine. For example, I can’t even use cd with a unc path, when I’m trying to run functions. Hmmm, Let me correct myself: I couldn’t on prior versions. Perhaps this is something that has been changed?
    Dan

  4. Jessee replied on :

    I would also add mfilename and fileparts to the list of useful file-handling functions.

  5. Dani HC replied on :

    Other way is:

    disp(strcat(’dirName’,filesep,’fileName’))

    filesep depend on OS (’\’ or ‘/’)

  6. Loren replied on :

    Thanks to all of you for your thoughts.

    Jessee, you are right that fileparts is useful for machine independence. I am less certain about mfilename but it might be true.

    I know that some MATLAB functionality in the past didn’t handle UNC pathnames but I am not sure if those restrictions still apply. I know that publishing used to have some trouble and it seems to work for me know in R2007a.

    –Loren

  7. aslak grinsted replied on :

    I can see the use of mfilename. Here’s some code i have in a mfile called wtcsignif…

    persistent mypath
    if isempty(mypath)
    mypath=strrep(which(’wtcsignif’),’wtcsignif.m’,”);
    end

    wtcsignif is called from many different paths, but i want it to always use its own directory as the cache directory. Here mfilename and fileparts would be better.

    My example is from here:
    http://www.pol.ac.uk/home/research/waveletcoherence/

  8. Tim Davis replied on :

    I’ve noticed that in recent MATLAB versions, “filesep” isn’t necessary, if relative paths are used. For example:

    cd ../dir1/dir2

    or

    cd dir3/dir4

    works on both Windows and Linux, but

    cd ..\dir1\dir2

    cd dir3\dir4

    works only on Windows. The “/” also works where other filenames are expected (opening files, the load command, and so on). So “/” works just fine on any platform; MATLAB must make the obvious modification internally, which is The Right Thing To Do. I recall that in some MATLAB version that “/” didn’t work in Windows, and now it does.

    As one who writes code that is supposed to port to any MATLAB, Windows/Linux/Mac/etc, this is a welcome fix.

    So do we really need filesep anymore? Just use “/”. If this is the case, then the “doc filesep” should be updated to suggest using “/” as the platform-independent file separator.

    This doesn’t apply to names like C:\whatever, which will always remain singularly Windows-ish.

  9. Loren replied on :

    Tim-

    filesep is still useful, especially if you might be using drive letters as part of your path on a PC. / has been the canonical file separator in MATLAB for as long as I can remember (but my memory does fade on some of these things these days!). It was even more crucial when VMS was around for the VAX and the olden days for the Mac OS.

    –loren

  10. NerdRoom@WAKEUP.com replied on :

    NerdRoom@WAKEUP.com

    Many Nerds won’t be returning. Some old timers I remember from last year, people like Trenchcoat Mafia, Silk Dragon Shirt, probably won’t be coming back next year.
    Spamming blogs I put their names up, immortalizing them, if only until the blog owner erases everything::::
    1. Trenchcoat Mafia
    2. Silk Dragon Shirt
    3. The Distinguished English Gentleman
    4. Beta Nerd, and of course
    5. Rosie The Transsexual
    Rosie’s original name was just Rosie, due to his rosie cheeks. They shared he has a high level of knowledge, a tactic the gods employ to create a false sense of security. This of course is the segment which they dump so many transsexuals into.
    I too enjoy irony, and therefore Rosie has now become Rosie The Transsexual.
    Who else has a nickname in the NerdRoom?

    I’d like to remind you many of the people in the NerdRoom are good men. I hope this is reflected in what they are allowed to learn and the progress they’re allowed to make.
    I’d also like to remind you their predecessors, REAL nerds from a generation ago who fill the computer swap meet, are WONDERFUL men, and since I likely won’t be going again I want to remember them as well.

    Actually the comparison of the two is a testiment to the devolution of society, which will be used as justification for the Apocalypse:::
    Today’s nerds are NOT wonderful men. They grew up with the internet and many consider pornography as an acceptable vice. They gamble freely, enjoy evil imagry in video games, and this issue is a microcosim of our deterioration.

  11. Arsen replied on :

    What would you recommend if all my programs have paths hardcoded into them? Like “load c:\myprogs\ver1\my_code”. I’m moving to Linux now and contemplating on what to do. Thanks!!

  12. Loren replied on :

    Arsen-

    You should recode them to use pathsep, etc. and not be so tightly bound to absolute paths. Some of your functions, if you have them, might take pieces of their paths as part of the input arguments, should that make sense.

    –loren

  13. Arsen replied on :

    Thank you, Loren!!
    How would you approach making matlabpath portable between Linux and Windows? I.e. if I have c”:\myprogs\ver1\my_code” in the matlabpath.

  14. Loren replied on :

    Arsen-

    I gave you my recommendations above. It depends on what the path is on the other operating system. Split the path up so you use filesep, pathsep, etc.

    –Loren

Leave a Reply


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Ljubomir Josifovski: I have a simple figure where the legend overlaps with the plot after it is created, but when...
  • Hoi: Hi Peter, I’m glad to hear that you guys have plans to improve the compiler quality. Quality-wise, I think...
  • Peter Webb: Hoi, Long-term, we certainly plan on further improving the quality of the MATLAB Compiler (and all of the...
  • Peter Webb: GALLOU, I think the information in comment #9 might help you as well. If you compile using -C, and place...
  • Peter Perkins: Jasmine, I’m not exactly sure of the situation that you’re describing. There’s no...
  • jasmine: Hi Loren, I am trying to store both numerical and categorical values to a dataset array. As the data size is...
  • GALLOU: Hi, We have some need about a deployement process. We have a application which is compiled by MatLab Compiler...
  • Hoi: With -C switch, I think ctfroot will be the cleanest solution as the root path. Thanks Peter! Even with the -C...
  • Peter Webb: Hoi and Gunnar, You can exercise more control over where the encrypted files are installed via the...
  • Steve L: Ol, What Dave said is true, the constructor and set functions must be included inside the classdef file, but...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.

Related Topics