Talk:Find common directory path: Difference between revisions
No edit summary |
m (Rename the function to avoid the implication that it finds the shortest common path (which would be much simpler).) |
||
Line 6: | Line 6: | ||
#include <stdio.h> |
#include <stdio.h> |
||
static void |
static void longestSharedPath(const char *fixed, char *moving) { |
||
char *t; |
char *t; |
||
unsigned n = strspn(moving, fixed); |
unsigned n = strspn(moving, fixed); |
||
Line 27: | Line 27: | ||
strcpy(tmp, dir_list[0]); |
strcpy(tmp, dir_list[0]); |
||
while (dir_list[++i]) { |
while (dir_list[++i]) { |
||
longestSharedPath(dir_list[i], tmp); |
|||
} |
} |
||
printf("%s\n", tmp); |
printf("%s\n", tmp); |
Revision as of 12:16, 14 April 2011
Much simpler version for the C language:
<lang C>
- define PATH_MAX 127
- include <string.h>
- include <stdio.h>
static void longestSharedPath(const char *fixed, char *moving) { char *t; unsigned n = strspn(moving, fixed); if (strlen(fixed) > n && strlen(moving) == n && fixed[n] == '/') return; strcpy(moving, fixed); moving[n] = '\0'; t = strrchr(moving, '/'); if (t && t != moving) *t = '\0'; }
int main() { char *dir_list[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", NULL }; int i = 0; char tmp[PATH_MAX]; strcpy(tmp, dir_list[0]); while (dir_list[++i]) { longestSharedPath(dir_list[i], tmp); } printf("%s\n", tmp); return 0; } </lang>
- I think that the last two lines of leastCommonPath are wrong: <lang c> t = strrchr(moving, '/');
if (t && t != moving) *t = '\0';</lang>. This should place the null after the slash, and not eliminate the slash otherwise the slash will not be available for future comparisons. If you change "coverage" to "dovetail" in the example data, I think this problem would raise its head. --Rdm 11:46, 14 April 2011 (UTC)
It is intended to work that way, and it works with "dovetail" also. The first conditional handles cases both with and without terminating slash. Try it. Per 12:07, 14 April 2011 (UTC)