How to handle this string concatenation in C in a reusable way

cfile handlingstrings

I've been writing a small C application that operates on files, and I've found that I have been copy+pasting this code around my functions:

char fullpath[PATH_MAX];
fullpath[0] = '\0';
strcat(fullpath, BASE_PATH);
strcat(fullpath, subdir);
strcat(fullpath, "/");
strcat(fullpath, filename);

// do something with fullpath...

Is there a better way? The first thought that comes to mind is to create a macro but I'm sure this is a common problem in C, and I'm wondering how others have solve it.

Best Answer

Reusable for a function like the one you describe means several things:

  • Doesn't assume the input is valid.
  • Uses sane defaults.
  • Prevents buffer overruns.
  • Returns some indication of success or failure.

In your case:

#define BASE_PATH "/path/to/wherever"
bool build_path(char *dest, size_t size, char *subdir, char *filename)
{
    // Don't assume the input is valid
    if ( (dest == NULL) || (size < 1) || (filename == NULL) ) {
        return false;
    }

    // Make no subdir work  (sane default behavior)
    if ( subdir == NULL ) {
        subdir = "";
    }

    // Prevent buffer overruns by using a safe formatting function
    size_t stored = snprintf(dest, size, BASE_PATH "/%s/%s", subdir, filename);

    // Returns success (true) if the path fit the buffer
    return ((stored+1) <= size);
}


char fullpath[PATH_MAX];
if ( ! build_path(fullpath, sizeof(fullpath), "foo/bar", "baz") ) {
   // Handle error
}
Related Topic