crelative-pathscandir

Relative Path Handling by scandir


Does the function scandir handle relative paths?

In other words, are the following two pieces of code equivalent?

int NUM = scandir("/home/hello/wait/../pqr/../../hello", &LIST, 0, alphasort);
int NUM = scandir("/home/hello", &LIST, 0, alphasort);

If not, is there some simple buit-in function to convert /home/hello/wait/../pqr/../../hello to /home/hello?


Solution

  • Does the function scandir handle relative paths?

    I believe the answer is yes. From posix scandir we know only that:

    The scandir() function shall scan the directory dir, [...]

    From posix definitions:

    3.129 Directory

    A file that contains directory entries. No two directory entries in the same directory have the same name

    The argument to scandir is char *, so it's a string. And from posix definitions we know that:

    3.271 Pathname

    A string that is used to identify a file. [...]

    Another section named 4.13 Pathname Resolution delves on how pathname is resolved, and tells us that:

    If the pathname does not begin with a <slash>, the predecessor of the first filename of the pathname shall be taken to be either the current working directory of the process [...] (such pathnames are referred to as "relative pathnames").

    So because scandir takes a pathname to a directory and because of how a pathname is resolved, yes, you can give relative paths to scandir.


    In other words

    It's not an "other word" - both pathnames you showed are absolute, not relative. Using dot-dot in a pathname doesn't make the pathname relative.

    are the following two pieces of code equivalent?

    Yes.


    is there some simple buit-in function to convert /home/hello/wait/../pqr/../../hello to /home/hello?

    There is no "builtin function" to canonicalize a pathname in any compiler I am aware of. There exists a completely normal function provided from POSIX for that purpose and is called realpath(). GNU library may allocated the returned string dynamically and it also has canonicalize_file_name.