command.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * File: command.c
  3. * Author: Arthur Brandao
  4. *
  5. * Created on 9 novembre 2018
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <unistd.h>
  10. #include "error.h"
  11. #include "str.h"
  12. #include "parser.h"
  13. #include "command.h"
  14. /* --- Extern --- */
  15. extern Error error;
  16. char* cmdlist[2] = {
  17. "cd",
  18. NULL
  19. };
  20. /* --- Fonctions publiques --- */
  21. boolean is_internal_cmd(const char* cmd){
  22. //Parcours tableau pour trouver correspondance
  23. for(int i = 0; cmdlist[i] != NULL; i++){
  24. printf("%s - %s\n", cmd, cmdlist[i]);
  25. if(strncmp(cmd, cmdlist[i], strlen(cmdlist[i]) + 1) == 0){
  26. return true;
  27. }
  28. }
  29. return false;
  30. }
  31. int launch_internal_command(Command* cmd){
  32. int result, length = strlen(cmd->name) + 1;
  33. //cd
  34. if(strncmp(cmd->name, cmdlist[0], length) == 0){
  35. result = cd(cmd->argc, cmd->argv);
  36. return result;
  37. }
  38. //Aucune commande
  39. else {
  40. return SHELL_FAIL;
  41. }
  42. }
  43. /* --- Commandes --- */
  44. int cd(int argc, char** argv) {
  45. //Si trop d'arguments
  46. if (argc > 2) {
  47. error.print("too many arguments : 1 required, %d given\n", argc - 1);
  48. return SHELL_FAIL;
  49. } else {
  50. //Si aucun argument on va à la racine
  51. if (argc == 1) {
  52. if (chdir("/") == ERR) {
  53. addperror("Erreur chdir()");
  54. return SHELL_ERR;
  55. }
  56. }
  57. //Sinon on va dans le dossier indiqué par l'utilisateur
  58. else {
  59. if (chdir(argv[1]) == ERR) {
  60. error.print("path does not exist\n");
  61. return SHELL_ERR;
  62. }
  63. }
  64. }
  65. return SHELL_OK;
  66. //show_current_dir("current working directory is: ", "\n");
  67. }