As part of C training, I wrote the following code to combine the directory name with the file name. For example: combine("/home/user", "filename") will result in /home/user/filename . It is expected that this feature will work on different platforms (at least in all popular Linux and Windows 32 and 64 bit distributions).
Here is the code.
const char* combine(const char* path1, const char* path2) { if(path1 == NULL && path2 == NULL) { return NULL; } if(path2 == NULL || strlen(path2) == 0) return path1; if(path1 == NULL || strlen(path1) == 0) return path2; char* directory_separator = ""; #ifdef WIN32 directory_separator = "\\"; #else directory_separator = "/"; #endif char p1[strlen(path1)];
I have the following questions regarding the above code.
- Consider the lines with numbers 1,2,3. All these 3 lines are designed to get the last item from the line. Looks like I'm writing more code for such a little thing. What is the correct method to get the last element from a
char* string. - To return the result, I highlight a new line using
malloc . I am not sure if this is the right way to do this. Is the subscriber expected to release the result? How can I tell the caller to free the result? Is there a low probability method available? - How do you rate the code (bad, average, good)? What are the areas that can be eliminated?
Any help would be great.
Edit
All problems discussed and implemented proposed changes are fixed. Here is the updated code.
void combine(char* destination, const char* path1, const char* path2) { if(path1 == NULL && path2 == NULL) { strcpy(destination, "");; } else if(path2 == NULL || strlen(path2) == 0) { strcpy(destination, path1); } else if(path1 == NULL || strlen(path1) == 0) { strcpy(destination, path2); } else { char directory_separator[] = "/"; #ifdef WIN32 directory_separator[0] = '\\'; #endif const char *last_char = path1; while(*last_char != '\0') last_char++; int append_directory_separator = 0; if(strcmp(last_char, directory_separator) != 0) { append_directory_separator = 1; } strcpy(destination, path1); if(append_directory_separator) strcat(destination, directory_separator); strcat(destination, path2); } }
In the new version, the caller must allocate enough buffer and send the combine method. This avoids problems with malloc and free . Here is the use
int main(int argc, char **argv) { const char *d = "/usr/bin"; const char* f = "filename.txt"; char result[strlen(d) + strlen(f) + 2]; combine(result, d, f); printf("%s\n", result); return 0; }
Any suggestions for improvement?
c string refactoring
Navaneeth KN
source share