Removing a path separator at the end of a line

I use the following code to move backward through the tree, and now I get a separator at the end, for example child / grandchild / <- I want to remove this separator. I do not know what to change in the algorithm for this.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node { struct node *parent; char *name; };

char *buildPath(node* node, bool use_register_name)
{
    struct node *temp = node;
    int length =0;
      do
      {
        length+=strlen(temp->name)+1; // for a slash;
        temp = temp->parent;
      } while(temp !=NULL);    
    char * buffer =malloc(length+1);
    buffer[0] = '\0';    
       do 
       {
         if(!use_register_name)
         {
            use_register_name=true;
            node = node->parent;
            continue;
         }
         char *name = strdup(node->name);
         strcat(buffer,"/");
         strrev(name);
         strcat(buffer,name);    

         node = node->parent;
         free(name);
       } while (node != NULL &&strcmp(node->name,"root")<0);    
    strrev(buffer);    
    return buffer;
}

int main(void)
{
    struct node node1 = { NULL, "root" };
    struct node node2 = { &node1, "child" };
    struct node node3 = { &node2, "grandchild" };    
    char * result = buildPath(&node3, false);    
    printf(result);    
    return EXIT_SUCCESS;
}
+4
source share
1 answer

Assuming that every result you get will have this trailing slash, you can simply remove it from the final output. In the code snippet below, I conditionally check that it resulthas at least one character and that the last character is a slash. If these conditions are true, I remove the slash.

char * result = buildPath(&node3, false);

if (result && *result) {                      // make sure result has at least
    if (result[strlen(result) - 1] == '/')    // one character
        result[strlen(result) - 1] = 0;
}

Update:

Here is a solution to your problem that modifies the algorithm itself. Try changing the code to the following:

int firstCall = 1; // flag to keep track of whether this is first call (leaf node)

do {
    if(!use_register_name)
    {
        use_register_name=true;
        node = node->parent;
        continue;
    }
    char *name = strdup(node->name);
    if (firstCall) {
        firstCall = 0;
    }
    else {
        // ONLY add this slash to a non-terminal node
        strcat(buffer,"/");
    }
    strrev(name);
    strcat(buffer,name);

    node = node->parent;
    free(name);
} while (node != NULL &&strcmp(node->name,"root")<0);

OP:

buffer = "/dlihcdnarg"        // note carefully this leading (really trailing) slash
buffer = "/dlihcdnarg/dlihc"

- , :

"child/grandchild/"

node ( ) , :

"child/grandchild"
+5

Source: https://habr.com/ru/post/1608953/


All Articles