How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in C

1 Answer

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

#define MAX_PARTS 128     // Maximum number of path components
#define MAX_LEN 256       // Maximum length of each component

// Function to simplify a Unix-style file path
char* simplifyPath(const char* path) {
    char* stack[MAX_PARTS];   // Stack to store valid path components
    int top = -1;             // Stack pointer
    int i = 0;
    int len = strlen(path);

    char temp[MAX_LEN];       // Temporary buffer to hold each path component

    while (i < len) {
        // Skip redundant slashes
        while (i < len && path[i] == '/')
            i++;

        int j = 0;
        // Extract the next path component
        while (i < len && path[i] != '/') {
            temp[j++] = path[i++];
        }
        temp[j] = '\0';  // Null-terminate the component

        // Ignore empty components and "."
        if (j == 0 || strcmp(temp, ".") == 0)
            continue;

        // Ignore ".." 
        if (strcmp(temp, "..") == 0)
            continue;

        // Valid component, push to stack
        stack[++top] = strdup(temp);
    }

    // Reconstruct the simplified path
    if (top == -1)
        return strdup("/");  // If stack is empty, return root

    char* result = malloc(MAX_PARTS * MAX_LEN);
    result[0] = '\0';

    for (int k = 0; k <= top; k++) {
        strcat(result, "/");
        strcat(result, stack[k]);
        free(stack[k]);  // Free each component after use
    }

    return result;
}

int main() {
    // Input path to be simplified
    const char* inputPath = "/home//foo/../bar/./unix/";

    // Call the simplifyPath function
    char* simplified = simplifyPath(inputPath);

    // Output the result
    printf("Simplified path: %s\n", simplified);

    // Free the result string
    free(simplified);

    return 0;
}


/*
run:

Simplified path: /home/foo/bar/unix

*/


/*
run:

Simplified path: /home/bar/unix

*/

 



answered Sep 7, 2025 by avibootz
...