0

I have this function which gets the given directory and filename and concat it by checking if the end of the directory contains / character and concatenating the string's for condition. My problem is that when i give the function a directory name and filename if the filname has \ it does not concat the string correctly. but when if the file does not contain any \ the output will be given.How can i fix the issue?.

Here is my C Code.

char * find_endwith_slash(char *dir_path, char *file_name)
{
    char full_path[1024];
    if (dir_path[strlen(dir_path) - 1] != '/')
    {
        sprintf(full_path, "%s/%s", dir_path, file_name);
    }
    else
    {
        sprintf(full_path, "%s%s", dir_path, file_name);
    }

    char * full_name = malloc(strlen(full_path) * sizeof(char));
    full_name = strdup(full_path);

    return full_name;



} 
devMe
  • 126
  • 10

1 Answers1

1

A more proper approach to conditionally concatenating path and file name:

char * find_endwith_slash_alt(const char *dir_path, const char *file_name) {
  size_t d_length = strlen(dir_path);
  size_t f_length = strlen(file_name);
  if (d_length > 0 && dir_path[d_length-1] == `/`) {
    d_length--;
  } 
  char *both = malloc(d_length + 1 + f_length + 1);
  if (both) {
    memcpy(both, dir_path, d_length);
    both[d_length] = '/';
    memcpy(both + d_length + 1, file_name, f_length + 1);
  }
  return both;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • What if `const char *file_name = "Fil\\eName"` such as `find_endwith_slash("Directory", "Fil\\eName");`? – Gaurav Pathak Dec 28 '22 at 17:30
  • @GauravPathak The result is `"Directory/Fil\\eName"`. If the path or file name are ill formed, the result is ill formed. Alternatively code could validate the path and file names, yet validation is really outside the goal (and OS specific) of this function and better handled in a separate validation function and called as needed. – chux - Reinstate Monica Dec 28 '22 at 17:46