ssl_des/src/base64/ft_base64.c

68 lines
1.2 KiB
C
Raw Normal View History

2019-02-10 23:11:01 +02:00
#include <stdio.h>
2019-02-07 23:22:40 +02:00
#include "libft.h"
#include "ft_base64.h"
2019-02-10 23:11:01 +02:00
#include "fcntl.h"
2019-02-21 00:33:54 +02:00
#include "sys/stat.h"
2019-02-07 23:22:40 +02:00
2019-02-21 00:33:54 +02:00
static int open_stream(char *filename, int flags, int mode)
2019-02-07 23:22:40 +02:00
{
2019-02-10 23:11:01 +02:00
int fd;
2019-02-21 00:33:54 +02:00
if ((fd = open((const char *)filename, flags, mode)) == -1)
2019-02-10 23:11:01 +02:00
{
perror("base64");
exit(1);
}
return fd;
2019-02-07 23:22:40 +02:00
}
static void init_flags(t_base64_flags *flags)
{
flags->decode = 0;
}
static void read_args
(
int argc,
char **argv,
t_base64_flags *flags,
t_base64_ctx *ctx
)
{
int i;
char *current_arg;
char *next_arg;
i = 0;
while(i < argc)
{
current_arg = argv[i];
next_arg = i + 1 < argc ? argv[i + 1] : NULL;
if (ft_strcmp(current_arg, "-d") == 0)
flags->decode = 1;
2019-02-21 00:33:54 +02:00
else if (ft_strcmp(current_arg, "-e") == 0 && ++i)
2019-02-07 23:22:40 +02:00
continue;
else if (ft_strcmp(current_arg, "-i") == 0)
2019-02-21 00:33:54 +02:00
ctx->input_fd = open_stream(next_arg, O_RDONLY, 0);
2019-02-07 23:22:40 +02:00
else if (ft_strcmp(current_arg, "-o") == 0)
2019-02-21 00:33:54 +02:00
ctx->output_fd = open_stream(next_arg, O_CREAT | O_WRONLY,
S_IRUSR | S_IWUSR);
else if (++i)
2019-02-07 23:22:40 +02:00
continue;
i++;
}
}
void ft_base64(int argc, char **argv)
{
t_base64_flags flags;
t_base64_ctx ctx;
init_flags(&flags);
2019-02-10 23:11:01 +02:00
ft_base64_init(&ctx);
2019-02-07 23:22:40 +02:00
read_args(argc, argv, &flags, &ctx);
if (flags.decode)
ft_base64_decode(&ctx);
else
ft_base64_encode(&ctx);
exit(0);
}