Add some sources

This commit is contained in:
Artur Tamborski 2018-12-01 18:10:17 +01:00
parent 37c36b25ba
commit 0548b71a72
4 changed files with 150 additions and 0 deletions

13
src/common.h Normal file
View File

@ -0,0 +1,13 @@
#ifndef COMMON_H
#define COMMON_H
#define CONCAT(x,y) _CONCAT(x,y)
#define _CONCAT(x,y) (x##y)
#define TOSTR(x) _TOSTR(x)
#define _TOSTR(x) (#x)
#endif /* COMMON_H */

65
src/icmd.c Normal file
View File

@ -0,0 +1,65 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include "icmd.h"
#include "common.h"
#define ICMDS_SIZE \
(sizeof(g_icmds) / sizeof(g_icmds[0]))
#define ICMD(name) \
{ \
.cmd = TOSTR(name), \
.len = sizeof(TOSTR(name)), \
.func = CONCAT(icmd_, name), \
}
struct icmd g_icmds[] =
{
ICMD(exit),
ICMD(cd),
ICMD(ls),
};
int
call_icmds(char *line)
{
size_t i;
for (i = 0; i < ICMDS_SIZE; i++)
{
printf("cmp: %s : %s \n", g_icmds[i].cmd, line);
if (strncmp(g_icmds[i].cmd, line, g_icmds[i].len) == 0)
return g_icmds[i].func(line);
}
return INT_MAX;
}
int
icmd_exit(char *line)
{
printf("exiting with reason: %s", line);
exit(0);
}
int
icmd_cd(char *line)
{
printf("I'm a cd! line: %s\n", line);
return 0;
}
int
icmd_ls(char *line)
{
printf("I'm a ls! line: %s\n", line);
return 1;
}

23
src/icmd.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef ICMD_H
#define ICMD_H
struct icmd
{
char *cmd;
int len;
int (*func)(char *);
};
/* interface */
int call_icmds(char *line);
/* internal commands as functions */
int icmd_exit(char *line);
int icmd_cd(char *line);
int icmd_ls(char *line);
#endif /* ICMD_H */

49
src/main.c Normal file
View File

@ -0,0 +1,49 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <limits.h>
#include "icmd.h"
/* should be enough */
#define CMD_LINE_MAX 1024
#define CMD_PATH_MAX 4096
int
die(char *s)
{
perror(s);
exit(-1);
}
int
main(int argc, char **argv)
{
char line[CMD_LINE_MAX];
char cwd[CMD_PATH_MAX];
char *pline = line;
int ret;
for (;;)
{
/* todo: does it really fail? */
if (getcwd(cwd, sizeof(cwd)) == NULL)
die("getcwd()");
printf("[%s] ", cwd);
fgets(line, sizeof(line), stdin);
ret = call_icmds(line);
if (ret == INT_MAX)
puts("no such internal command, going on...");
else if (ret == 0)
puts("internal command succeded!");
else
puts("internal command succeded!");
}
return 0;
}