Search code examples
pathposixdirname

Is it safe to split a path on '/' to parse it?


I am trying to get all directories in a path. For example, from a/b/c/d.e I would like to get a, a/b, and a/b/c. I can achieve this by calling functions like posixdirname several times. The problem is with paths like a/b/c/. I would like to get a, a/b, and a/b/c. Since there is a / following c, c should be a directory that I would like to list. But functions like dirname return a/b instead of a/b/c when given a/b/c/ as input.

Can I just split on / to get the list of directories or is there an edge case where this wouldn't work?


Solution

  • The only special cases I know are

    1. with file name at the end
    2. with a / at the end
    3. with a folder name called a.e (may or may be not at the end)
    4. symbolic link
    5. Windows path (which is using \ but I think it is not applying in your case)
    6. User input error, put multiple /. e.g. /tmp//something which is supported in some programmes

    If your function is supporting all of the above cases, I think it is fine.