How to get a normalized (canonical) file path in Linux "even if the file path does not exist in the file system"? (In program C))

I studied a lot of this topic, but could not get anything significant. By normalizing / canonicalize, I want to remove all "..", ".", Multiple slashes, etc. From the file path and get a simple absolute path. eg

"/rootdir/dir1/dir2/dir3/../././././dir4//////////" before "/ RootDir / dir1 / dir2 / dir4"

On Windows, I have GetFullPathName () , and I can get the name canonical filepath, but for Linux I can’t find an API that can do the same job for me, realpath () exists, but even realpath () requires the path to the file was present in the file system in order to be able to output a normalized path , for example. if the path / rootdir / dir 1 / dir2 / dir4 is not in the file system - realpath () will cause an error with the above complex input of the file path. Is there a way by which you can get a normalized path to a file , even if it does not exist on the file system ?

+5
source share
2

realpath (3) .
GNU (https://www.gnu.org/software/coreutils/) realpath (1), realpath (3), : < /" > -m, --canonicalize-missing
canonicalize_filename_mode() lib/canonicalize.c coreutils.

+2

canonicalize_filename_mode() Gnulib - , ( GPL)

, cwalk:

#define _GNU_SOURCE

#include <unistd.h>
#include <stdlib.h>

#include "cwalk.h"

/* extended version of canonicalize_file_name(3) that can handle non existing paths*/
static char *canonicalize_file_name_missing(const char *path) {
    char *resolved_path = canonicalize_file_name(path);
    if (resolved_path != NULL) {
        return resolved_path;
    }
    /* handle missing files*/
    char *cwd = get_current_dir_name();
    if (cwd == NULL) {
        /* cannot detect current working directory */
        return NULL;
    }
    size_t resolved_path_len = cwk_path_get_absolute(cwd, path, NULL, 0);
    if (resolved_path_len == 0) {
        return NULL;
    }
    resolved_path = malloc(resolved_path_len + 1);
    cwk_path_get_absolute(cwd, path, resolved_path, resolved_path_len + 1);
    free(cwd);
    return resolved_path;
}
0

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


All Articles