mysh.c 2.4 KB

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