mysh.c 2.7 KB

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