/
Problems with concatenating directories

Problems with concatenating directories

Don’t append file paths manually like this:

COLstring FilePath; FilePath = CFGrootDir() + "\config.cfg";

This is bad practice.

A frequent source of bugs with functions that give directory paths is forgetting to put a trailing directory slash at the end of the path.

We have two problems:

  • Windows and POSIX operating systems use different slash characters - windows uses \ and everyone else uses /

  • The other problem is either omitting the trailing slash or accidentally writing code which adds a double slash.

What are reasonable ways to solve this problem?

Firstly in our library system we have a FIL_PATH_SEP_NATIVE constant which will give the slash character as represented by the operating system.

Then we have FILaddPathSeparator. This function will add a trailing slash character if and only if it needs it. i.e. it won’t add a double slash.

Another useful function is FILpathAppend. This function takes two paths and adds them together correctly taking into account trailing slashes and simplifies the path removing ./ and ../ patterns.

It is generally best practice to make sure you solve these problems at the lowest level in your code. Otherwise if individual programmers solving this problem independently using code calling library code which generates a directory path then this is results in more bugs like double trailing slashes when the problem is fixed at a lower level.

The above code could be better written as:

COLstring FilePath; FilePath = FILpathAppend(CFGrootDir(),"config.cfg"); // or FilePath = CFGrootDir(); FILaddPathSeparator(FilePath); FilePath += "config.cfg";

The first form is briefer.

Related content

Add in FIL library
Add in FIL library
More like this
hl7.parse and hl7.message - dealing with windows paths
hl7.parse and hl7.message - dealing with windows paths
More like this
Understanding search paths
Understanding search paths
More like this
Simple make system - putting it all together
Simple make system - putting it all together
More like this
Understanding File paths
Understanding File paths
More like this