Advertisement
Guest User

Untitled

a guest
Oct 2nd, 2014
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <dirent.h> // opendir, closedir, readdir, struct dirent
  6. #include <errno.h>
  7. #include <unistd.h>
  8. #include <string.h>
  9.  
  10. /***** FONCTIONS *****/
  11.  
  12. void filetype(const char * dirname, const char * filename) {
  13. struct stat entry_stat;
  14. char * path = NULL;
  15. // nom_dossier + '/' + nom_fichier + '\0'
  16. path = (char *)malloc(sizeof(char) * (strlen(dirname) + 1 + strlen(filename) + 1));
  17. strcpy(path, dirname);
  18. strcat(path, "/");
  19. strcat(path, filename);
  20. if(stat(path, &entry_stat) == -1) {
  21. perror("stat");
  22. exit(EXIT_FAILURE);
  23. }
  24. printf("[");
  25.  
  26. if(S_ISDIR(entry_stat.st_mode)) {
  27. printf("rep.");
  28. } else if(S_ISREG(entry_stat.st_mode)) {
  29. printf("fic");
  30. }
  31. printf("] ");
  32. free(path);
  33. }
  34.  
  35. void ls(char * dirname) {
  36. struct dirent * lecture;
  37. DIR * rep;
  38. rep = opendir(dirname);
  39. if(rep == NULL) {
  40. printf("Répertoire inexistant\n");
  41. exit(EXIT_SUCCESS);
  42. }
  43. while ((lecture = readdir(rep))) {
  44. if(lecture == NULL && errno == EBADF) {
  45. fprintf(stderr, "'%s' is not a directory.\n", dirname);
  46. return;
  47. }
  48. if(strcmp(lecture->d_name, ".") != 0 && strcmp(lecture->d_name, "..") != 0) {
  49. filetype(dirname, lecture->d_name);
  50. printf("%s\n", lecture->d_name);
  51. }
  52. }
  53. closedir(rep);
  54. }
  55.  
  56. /***** PROGRAMME PRINCIPAL *****/
  57.  
  58. int main(int argc, char * argv[]) {
  59. char * dirname = ".";
  60. if(argc > 1) {
  61. dirname = argv[1];
  62. }
  63. ls(dirname);
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement