Question

I have a list of files, but some look like this:

Got file //efi/./refit/icons/tool_rescue.icns

the problem is, I need to count the level depth of the file (meaning, counting the /'s.) I would like to just eliminate unrequired ./'s, //'s, etc from the string. Below is my code as I have it now. The only problem is, with it running, I get some paths like this

Got file /Users/.bin/tcsh

that file seemed to be /Users/../bin/tcsh. I know the function is a good start, but a little help in the right direction would be nice.

void minimize_path(char *s)
{
    int i, j;
    do
    {
        for (i = 0; i < strlen(s); i++)
        {
            if (s[i] == '/' && s[i + 1] == '/') //double /
                for (j = i; j < strlen(s) + 1; j++)
                    s[j] = s[j + 1];
            if (s[i] == '.' && s[i + 1] == '/')
                for (j = i; j < strlen(s) + 1; j++)
                    s[j] = s[j + 2];
        }
    } while (strstr(s, "//") != NULL);
}
Was it helpful?

Solution

This eliminates the double dots:

     if (s[i] == '.' && s[i + 1] == '/')
            for (j = i; j < strlen(s) + 1; j++)
                s[j] = s[j + 2];

Maybe this'll be better to verify there wasn't a preceding dot:

     if ((i == 0 || (i > 0 && s[i-1] != '.')) && s[i] == '.' && s[i + 1] == '/')
            for (j = i; j < strlen(s) + 1; j++)
                s[j] = s[j + 2];

Note: If you want to do this "the right way" you may want to look at lexical analysis and tokenization.

realpath is another option if you can use the available library functions:

reuts@reuts-K53SD:~/cc$ cat test.c 
#include <stdio.h>
#include <limits.h> // PATH_MAX

int main(int argc, char ** argv)
{

        char rp[PATH_MAX+1];
        realpath("/usr/../usr/./bin", rp);
        printf("%s\n", rp);

        return 1;
}
reuts@reuts-K53SD:~/cc$ gcc test.c && ./a.out 
/usr/bin
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top