winapi

Why does PathRelativePathTo() have to know whether the destination is a file or a directory?


PathRelativePathTo has this signature (the W version):

BOOL PathRelativePathToW(
  [out] LPWSTR  pszPath,
  [in]  LPCWSTR pszFrom,
  [in]  DWORD   dwAttrFrom,
  [in]  LPCWSTR pszTo,
  [in]  DWORD   dwAttrTo
);

The last parameter can be set to FILE_ATTRIBUTE_DIRECTORY to let the function know that pszTo is a directory or to 0 if it is a file. Why is this distinction necessary?

Consider this case (pszFrom is a directory):

pszFrom:   C:\foo\bar
pszTo:     C:\foo\baz
result:    ..\baz

It does not make a difference whether baz is a file or a directory, the result would still be the same.

Consider this case:

pszFrom:   C:\foo\bar
pszTo:     C:\foo
result:    ..

Granted, the caller could claim -- incorrectly -- that C:\foo is a file when it clearly must be a directory, but why would the function care? (Garbage in, garbage out.)

Is there a case where a different setting of dwAttrTo leads to different results (assuming all other arguments are identical)?


Solution

  • The function doesn't "care" but my guess would be that this is simply a "convenience" for the caller.

    If you set the attribute value to anything other than FILE_ATTRIBUTE_DIRECTORY, the final component of that path is removed from the calculation altogether.

    This lets you pass two fully qualified filenames to the function and find the relative path between their parent folders.

    In the example you gave:

    pszFrom:   C:\foo\bar (FILE_ATTRIBUTE_DIRECTORY)
    pszTo:     C:\foo\baz (FILE_ATTRIBUTE_DIRECTORY)
    result:    ..\baz
    
    pszFrom:   C:\foo\bar (FILE_ATTRIBUTE_NORMAL)
    pszTo:     C:\foo\baz (FILE_ATTRIBUTE_NORMAL)
    result:    .