Search code examples
cfilesystemsportabilityansi-c

Portable plain C function for extracting filename from path


I am looking for a portable way to extract the filename from a path string in ANSI C.

The paths are like the following ones:

C:\tmp\abc.txt

C:/tmp/abc.txt

c:/tmp\abc.txt

../abc.txt

c:tmp/abc.txt

c:abc.txt

abc.txt

./abc.txt

/home/user/abc.txt

/home/.././var/tmp/abc.txt

For each case I want to extract the "abc.txt"

Is there a general solution available? (I haven't found any here and with google)


Solution

  • There is nothing in the C standard that specifies such a function or that requires implementations to provide one.

    Furthermore, it is not possible to implement one yourself without tailoring it specifically to the target environment. Proof:

    • On a Windows system, the file name portion of abc\def.txt is def.txt.
    • On a macOS system, the file name portion of abc\def.txt is abc\def.txt.

    Since the proper result for identical input is different on different systems, a function independent of the file name syntax for target environment cannot implement this.

    Therefore, any such function must be written either for a specific implementation or implementations or must take into account and adapt itself for the environment it is compiled for.

    I am not aware of any software that provides such a function, which is not to say none such exists.