In my opinion, as a professional programmer, you must not write code like that. You must either write your own path concatenation function, or use the one provided by the platform.
If it's Windows you should use the _makepath
function. For greater safety, use the _makepath_s
function. It will be more careful than you are. I'm sure Posix has something similar.
If you must write your own, simple concatenation is just not good enough. You need to check for proper handling of delimiters, trailing slash on directories, leading period on extensions, null arguments and all that stuff. The good news is that if you do it once it's done.
In the more general case of concatenating strings, you are very hampered by your apparent decision to stick with C rather than C++. I would again recommend writing your own function with variable arguments (vararg
) and using strcat_s()
for security. Something like:
bool strcat_multi_s(char *destination, size_t maxlength, ...); // return false on overflow
I leave the coding as an exercise for the reader.
sprintf(fullpath, "%s%s/%s", BASE_PATH, subdir, filename)
? Besides being less wordy, it'd also resolve your Schlemiel the Painter issue. :Pstrcat
isn't any safer, really, except for the fixed argument list.printf
andscanf
-family functions and any custom functions that forward their arguments to these (with a special annotation).