Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string.h>
- #include <stdlib.h>
- #include <errno.h>
- static char *path_remove_reldir(const char * path, char *normalized_path)
- {
- #ifdef WIN32
- // Not implemented (I think nobody needs it)
- errno = EINVAL;
- return NULL;
- #else
- int ilastsep = -1;
- int iread = 0;
- int iwrite = 0;
- if (path == NULL || normalized_path == NULL)
- {
- errno = EINVAL;
- return NULL;
- }
- do
- {
- if (path[iread] == PATH_SEPARATOR_CHAR || path[iread] == '\0')
- {
- int len_dir = iread - (ilastsep + 1);
- if (len_dir == 2 && path[ilastsep + 1] == '.' && path[ilastsep + 2] == '.')
- {
- // ".."
- // Find the separator of parent directory.
- iwrite -= 2;
- while (iwrite >= 0 && normalized_path[iwrite] != PATH_SEPARATOR_CHAR)
- {
- iwrite--;
- }
- // Raise an error if not available.
- if (iwrite < 0)
- {
- normalized_path[0] = '\0';
- errno = EINVAL;
- return NULL;
- }
- // Prevent erasing root directory symbol by NUL.
- if (iwrite == 0 && normalized_path[iwrite] == PATH_SEPARATOR_CHAR &&
- path[iread] == '\0')
- {
- iwrite++;
- }
- // overwrite separator/NUL character.
- normalized_path[iwrite] = path[iread];
- iwrite++;
- }
- else
- {
- if (len_dir == 1 && path[ilastsep + 1] == '.')
- {
- // note that "./" must not be converted to "/".
- if (iwrite > 0)
- {
- iwrite--;
- // prevent erasing root directory symbol by NUL.
- if (iwrite == 0 && normalized_path[iwrite] == PATH_SEPARATOR_CHAR &&
- path[iread] == '\0')
- {
- iwrite++;
- }
- normalized_path[iwrite] = path[iread];
- iwrite++;
- }
- }
- else
- {
- memcpy(&normalized_path[iwrite], &path[ilastsep + 1], len_dir);
- iwrite += len_dir;
- normalized_path[iwrite] = path[iread];
- iwrite++;
- }
- }
- ilastsep = iread;
- }
- } while (path[iread++] != '\0');
- return normalized_path;
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement