tmurase-42 / minishell

dev
0 stars 0 forks source link

buildin関数としてpwdコマンドの実装 #8

Open tmurase-42 opened 3 years ago

tmurase-42 commented 3 years ago

pwd without any options

dofuta commented 3 years ago
#include <stdlib.h>
#include <sys/errno.h>
#include "minishell.h"
#include "libft/libft.h"

char    **split_skip_str(char **split, char *str, int *cnt)
{
    char    **ret;
    int     i;
    int     j;

    i = -1;
    *cnt = 0;
    while (split[++i])
    {
        if (ft_strcmp(split[i], str) == 0)
            (*cnt)++;
    }
    if ((ret = malloc(sizeof(char *) * (i - (*cnt) + 1))) == NULL)
        die(strerror(errno));
    i = -1;
    j = 0;
    while (split[++i])
    {
        if (ft_strcmp(split[i], str) != 0)
            ret[j++] = ft_strdup(split[i]);
    }
    ret[j] = NULL;
    ft_split_free_null(split);
    free(str);
    return (ret);
}

char    *split_join_cnt(char **split, int *cnt)
{
    char    *ret;
    int     i;
    int     j;

    i = -1;
    while (split[++i])
        ;
    j = i - *cnt;
    i = 0;
    ret = ft_strdup("");
    while (i < j)
    {
        ret = ft_strjoin_chr_free(ret, ft_strdup(split[i]), '/');
        i++;
    }
    ft_split_free_null(split);
    return (ret);
}

char    *format_pwd(char *pwd, char *argv)
{
    char    *path;
    char    **tmp;
    int     slasla;
    int     cnt;

    slasla = is_path_slasla(pwd);
    path = ft_strjoin_chr(pwd, argv, '/');
    free(pwd);
    free(argv);
    tmp = split_skip_str(ft_split(path, '/'), ft_strdup("."), &cnt);
    free(path);
    tmp = split_skip_str(tmp, ft_strdup(".."), &cnt);
    path = split_join_cnt(tmp, &cnt);
    if (slasla == 1)
    {
        if (path[0] == '\0')
            path = ft_strjoin_chr_free(ft_strdup("//"), path, '\0');
        else
            path = ft_strjoin_free(ft_strdup("/"), path);
    }
    if (path[0] == '\0' && slasla == 0)
        path = ft_strjoin_chr_free(ft_strdup("/"), path, '\0');
    return (path);
}

char    *get_pwd(void)
{
    if (env_get(g_env, "PWD") == NULL)
        return ("");
    return (env_get(g_env, "PWD")->value);
}

int     ft_pwd(void)
{
    ft_putstr_fd(g_pwd, 1);
    ft_putstr_fd("\n", 1);
    return (0);
}