mysh.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * File: mysh.c
  3. * Author: Arthur Brandao
  4. *
  5. * Created on 31 octobre 2018, 12:43
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <unistd.h>
  10. #include "error.h"
  11. #include "parser.h"
  12. #include "mysh.h"
  13. /* --- Fonctions privées --- */
  14. void test_write() {
  15. char* a = "azerty\n";
  16. int tmp = write(1, a, strlen(a));
  17. printf("%d\n", tmp);
  18. }
  19. /* --- Fonctions utilitaires --- */
  20. void show_current_dir(const char* before, const char* after) {
  21. char buffer[BUFFER_SIZE];
  22. if (getcwd(buffer, sizeof (buffer)) == NULL) {
  23. perror("Erreur getcwd() : ");
  24. } else {
  25. if(before == NULL && after == NULL){
  26. printf("%s", buffer);
  27. } else if(before == NULL){
  28. printf("%s%s", buffer, after);
  29. } else if(after == NULL){
  30. printf("%s%s", before, buffer);
  31. } else {
  32. printf("%s%s%s", before, buffer, after);
  33. }
  34. }
  35. }
  36. /* --- Main --- */
  37. int main(int argc, char* argv[]) {
  38. CommandTab ct;
  39. char str[BUFFER_SIZE];
  40. int a;
  41. //Recup ligne
  42. //printf("%s\n", fgets(str, 500, stdin));&
  43. memset(str, 0, 500);
  44. a = read(STDIN, str, 500);
  45. printf("%s\n", str);
  46. //Separe les commandes
  47. a = parse_line(&ct, str);
  48. if(a == SHELL_ERR){
  49. serror("Erreur lors du parse de la ligne");
  50. exit(EXIT_FAILURE);
  51. }
  52. //Parse les commandes
  53. a = parse_all_command(&ct);
  54. if(a == SHELL_FAIL){
  55. serror("Erreur lors du parse des commandes");
  56. exit(EXIT_FAILURE);
  57. }
  58. //Affiche resultat
  59. for (int i = 0; i < ct.length; i++) {
  60. Command* c = ct.cmd[i];
  61. printf("Commande %d (%s) : \n", i, c->name);
  62. for (int j = 0; j < c->argc; j++) {
  63. printf(" Argument %d : %s\n", j, c->argv[j]);
  64. }
  65. printf("Commande en fond : %d\n\n", ct.bck);
  66. }
  67. //Supprime
  68. clean_command(&ct);
  69. return (EXIT_SUCCESS);
  70. }
  71. /* --- Commandes internes --- */
  72. void cd(int argc, char** argv) {
  73. //Si trop d'arguments
  74. if (argc > 2) {
  75. printf("too many arguments : 1 required, %d given\n", argc - 1);
  76. } else {
  77. //Si aucun argument on vas à la racine
  78. if (argc == 1) {
  79. if (chdir("/") == ERR) {
  80. perror("Erreur chdir() : ");
  81. }
  82. } //Sinon on va dans le dossier indiqué par l'utilisateur
  83. else {
  84. if (chdir(argv[1]) == ERR) {
  85. printf("path does not exist\n");
  86. }
  87. }
  88. }
  89. //show_current_dir("current working directory is: ", "\n");
  90. }