diff --git a/Makefile b/Makefile index 635e9c8..9898526 100644 --- a/Makefile +++ b/Makefile @@ -22,6 +22,7 @@ srcs = \ src/env_get.c \ src/env_manip.c \ src/env_manip_utils.c \ + src/ft_errno.c \ src/parser/matchers/metacharacter.c \ objs = $(srcs:.c=.o) diff --git a/src/ft_errno.c b/src/ft_errno.c new file mode 100644 index 0000000..94ef2a3 --- /dev/null +++ b/src/ft_errno.c @@ -0,0 +1,69 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_errno.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: khais +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2025/02/19 12:53/26 by khais #+# #+# */ +/* Updated: 2025/02/19 12:53:26 by khais ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "ft_errno.h" +#include "libft.h" +#include +#include + +/* +** get or set ft_errno +** +** if errno is FT_EGET, return ft_errno and do not set it +** +** else set ft_errno to errno, and return the previous value of ft_errno +*/ +t_errno ft_errno(t_errno errno) +{ + static t_errno ft_errno = FT_ESUCCESS; + t_errno ft_errno_backup; + + if (errno != FT_EGET) + { + ft_errno_backup = ft_errno; + ft_errno = errno; + return (ft_errno_backup); + } + return (ft_errno); +} + +/* +** get the current value of ft_errno +*/ +t_errno ft_errno_get(void) +{ + return (ft_errno(FT_EGET)); +} + +char *ft_strerror(t_errno errno) +{ + static char *strs[] = { + [FT_ESUCCESS] = "Success", + }; + + if (errno >= 0 && errno < FT_EMAXERRNO) + return (strs[errno]); + return ("Invalid error code"); +} + +t_errno ft_perror(char *desc) +{ + if (ft_errno_get() == FT_EERRNO) + perror(desc); + else + { + if (desc != NULL && desc[0] != '\0') + ft_dprintf(STDERR_FILENO, "%s: ", desc); + ft_dprintf(STDERR_FILENO, "%s\n", ft_strerror(ft_errno_get())); + } + return (ft_errno_get()); +} diff --git a/src/ft_errno.h b/src/ft_errno.h new file mode 100644 index 0000000..80a6076 --- /dev/null +++ b/src/ft_errno.h @@ -0,0 +1,29 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_errno.h :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: khais +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2025/02/19 12:53/30 by khais #+# #+# */ +/* Updated: 2025/02/19 12:53:30 by khais ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#ifndef FT_ERRNO_H +# define FT_ERRNO_H + +typedef enum e_errno +{ + FT_EERRNO = -2, + FT_EGET = -1, + FT_ESUCCESS = 0, + FT_EMAXERRNO, +} t_errno; + +t_errno ft_errno(t_errno errno); +t_errno ft_errno_get(void); +char *ft_strerror(t_errno errno); +t_errno ft_perror(char *desc); + +#endif