mysh.c 2.6 KB

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