summaryrefslogtreecommitdiff
path: root/main.c
blob: 650d646b05ea637dcabc808529fd24aaa5f4d0a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>

#define MAX_HISTORY 100
#define MAX_COMMAND_LENGTH 255

struct com_struct {
    char *com;
    char *arg;
};

void test() {
    printf("\nprint to output");
}

// exit() command
void exit_() {
    exit(0);
}

// ls command
// get the requested path and put it into a const later on when getting the user input

void ls(const char *path) {
    struct dirent *entry;
    DIR *dP = opendir(path);

    // check if the directory got opened successfully
    if (dP == NULL) {
        perror("opendir");
        return;
    }

    // print the folder|directory name
    while ((entry = readdir(dP)) != NULL) {
        printf("%s", entry->d_name);
    }
    closedir(dP);
}

struct com_struct split_command(char *input) {
    struct com_struct NEW_COMMAND;

    const char *command = strtok(input, " ");
    const char *argument = strtok(NULL, " ");


    if (command != NULL) {
        NEW_COMMAND.com = strdup(command);
    } else
    {
        printf("failed, null pointer detected");
        free(command);
    }

    if (argument != NULL) {
        NEW_COMMAND.arg = strdup(argument);
    } else {
        printf("failed, null pointer detected");
        free(argument);
    }
    return NEW_COMMAND;
}

int main(void) {
    while (1) {
        char *input = malloc(sizeof(char *) * MAX_COMMAND_LENGTH);

        printf("\n$ ");

        fgets(input, MAX_COMMAND_LENGTH, stdin);
        const struct com_struct new_input = split_command(input);

        new_input.com[strcspn(new_input.com, "\n")] = '\0';


        if (strcmp(new_input.com, "exit\n") == 0) {
            exit_();
            free(input);
            free(new_input.com);
            free(new_input.arg);
            return 0;
        }
        if (strcmp(new_input.com, "ls\n") == 0) {
            printf("DETECTED LS COMMAND");
            if (new_input.arg == NULL) {
                printf("\nARGUMENT NOT DEFINED");
                free(new_input.com);
                free(new_input.arg);
                continue;
            }
            ls(new_input.arg);
        }
        if (strcmp(new_input.com, "echo\n") == 0) {
            printf("DETECTED ECHO COMMAND");
            printf("%s", new_input.arg);
            free(new_input.arg);
        }
    }
}