From 9702e0049dd72677dada4f747223d2e49a3153e6 Mon Sep 17 00:00:00 2001
From: "dario.genga" <dario.genga@etu.hesge.ch>
Date: Mon, 29 Nov 2021 20:27:03 +0100
Subject: [PATCH] Add command line execution

The program can now be executed by command line with the following
syntax :

./stack [array_length] [arguments]

This will sort the values passed as arguments and print them in the
console.

Also uptaded the README file with this new execution.
---
 README.md | 16 +++++++++++++++-
 main.c    | 34 ++++++++++++++++++++++++++++++++--
 2 files changed, 47 insertions(+), 3 deletions(-)

diff --git a/README.md b/README.md
index 0e24627..a6b6ad8 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,18 @@
 
 Use this command to compile the project.
 
+### Run the program
+
+Execute the file _stack_ to start the program.
+
+The program must have the following arguments :
+
+>./stack [array_length] [elements]
+
+Example : 
+
+>./stack 5 0 -1 2 7 4
+
 ### Clean the project
 > `make clean`
 
@@ -18,5 +30,7 @@ Use this command to clean the project.
 
 ### Run the tests
 > `make test`
+>
+> `./test`
 
-Use this command to start the tests.
\ No newline at end of file
+Use this command to compile and start the tests.
diff --git a/main.c b/main.c
index 5d111c2..f6ca00e 100644
--- a/main.c
+++ b/main.c
@@ -6,8 +6,38 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include "stack.h"
+#define  ARGS_MIN 2
+#define  ARG_INDEX_array_size 1
 
-int main() {
 
-    return EXIT_SUCCESS;
+void print_array(int *array, int array_size) {
+    for (int i = 0; i < array_size; i++) {
+        printf("%d ", array[i]);
+    }
+    printf("\n");
 }
+
+int main(int argc, char **argv) {
+    if (argc < ARGS_MIN) {
+        printf("Missing arguments.\n");
+        return EXIT_FAILURE;
+    }
+
+    int array_size = atoi(argv[ARG_INDEX_array_size]);
+
+    if (array_size != argc - ARGS_MIN || array_size == 0) {
+        printf("The number of element must correspond to the size of the array.\n");
+        return EXIT_FAILURE;
+    }
+    int *array = malloc(array_size * sizeof(int));
+
+    for (int i = 0; i < argc - ARGS_MIN; i++) {
+        array[i] = atoi(argv[i + ARGS_MIN]);
+    }
+    int* sorted_array = sort(array, array_size);
+    print_array(sorted_array, array_size);
+
+    free(sorted_array);
+    free(array);
+    return EXIT_SUCCESS;
+}
\ No newline at end of file
-- 
GitLab