ls3.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* ls3.c
  2. * purpose list contents of directory or directories
  3. * action if no args, use . else list files in args
  4. * note uses stat and pwd.h and grp.h
  5. * BUG: try ls3 /tmp
  6. */
  7. #include <stdio.h>
  8. #include <sys/types.h>
  9. #include <dirent.h>
  10. #include <sys/stat.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #include "mode_to_letters.h"
  14. #include "gid_to_name.h"
  15. #include "show_file_info.h"
  16. #include "uid_to_name.h"
  17. void do_ls(char[]);
  18. void dostat(char *, char *);
  19. int main(int ac, char *av[])
  20. {
  21. if ( ac == 1 )
  22. do_ls( "." );
  23. else
  24. while ( --ac ){
  25. printf("%s:\n", *++av );
  26. do_ls( *av );
  27. }
  28. }
  29. void do_ls( char dirname[] )
  30. /*
  31. * List files in directory called dirname
  32. */
  33. {
  34. DIR *dir_ptr; // Directory pointer
  35. struct dirent *direntp; // Each entry in directory
  36. if ( (dir_ptr = opendir(dirname)) == NULL ) // Open directory
  37. {
  38. fprintf(stderr, "ls3: cannot open %s\n", dirname);
  39. }
  40. else
  41. {
  42. // Read each entry in the directory
  43. while ( (direntp = readdir(dir_ptr)) != NULL )
  44. {
  45. // Skip . and .. directories
  46. if ( strcmp(direntp->d_name, ".") == 0 || strcmp(direntp->d_name, "..") == 0 )
  47. continue;
  48. // Construct the full path
  49. char *full_path = (char *)malloc(strlen(dirname) + strlen(direntp->d_name) + 2); // +2 for '/' and '\0'
  50. if (!full_path) {
  51. fprintf(stderr, "Memory allocation error\n");
  52. closedir(dir_ptr);
  53. return;
  54. }
  55. // Concatenate the directory path and file name
  56. if (dirname[strlen(dirname) - 1] == '/') // If dirname ends with '/', just concatenate
  57. sprintf(full_path, "%s%s", dirname, direntp->d_name);
  58. else // If dirname doesn't end with '/', add a '/'
  59. sprintf(full_path, "%s/%s", dirname, direntp->d_name);
  60. // Call dostat to display file info
  61. dostat(full_path, direntp->d_name);
  62. // Free the allocated memory for full_path
  63. free(full_path);
  64. }
  65. closedir(dir_ptr);
  66. }
  67. }
  68. void dostat( char *full_path, char *filename )
  69. {
  70. struct stat info;
  71. if ( stat(full_path, &info) == -1 ) // Cannot stat file
  72. perror(filename); // Show error
  73. else // Show file info
  74. show_file_info(filename, &info);
  75. }