Advertisement
alexarcan

os_lab5_directory_ex

Oct 26th, 2015
347
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1.  
  2. /* sample program to illustrate the opendir(), readdir() and stat()
  3. system calls
  4.  
  5. it lists all files in the given directory, and adds an asterisk
  6. to each one which is a subdirectory */
  7.  
  8. #include <sys/types.h>
  9. #include <sys/dir.h>
  10. #include<stdio.h>
  11. #include<sys/stat.h>
  12. #include<fcntl.h>
  13. #include<unistd.h>
  14. #include<stdlib.h>
  15. #include<ctype.h>
  16. #include<string.h>
  17.  
  18. #define MAX_CHARS 200
  19.  
  20. int CharsRead,Tmp; /* number of characters read from a directory entry */
  21. struct direct *DirEntryPtr; /* pointer to a directory entry */
  22. DIR *DirPtr; /* pointer to the directory */
  23. struct stat Stat;
  24. char Path[MAX_CHARS];
  25.  
  26.  
  27.  
  28. int main(int argc, char *argv[])
  29.  
  30. { DirPtr = opendir(argv[1]);
  31. while (1) {
  32. DirEntryPtr = readdir(DirPtr);
  33. if (DirEntryPtr == 0) break; /* reached end of directory entries */
  34. /* process file (other than . and ..) */
  35. if (strcmp(DirEntryPtr->d_name,".") != 0 &&
  36. strcmp(DirEntryPtr->d_name,"..") != 0) {
  37. /* print file name */
  38. printf("%s",DirEntryPtr->d_name);
  39. /* build full path name of the file, for stat() */
  40. Path[0] = 0;
  41. strcat(Path,argv[1]);
  42. strcat(Path,"/");
  43. strcat(Path,DirEntryPtr->d_name);
  44. Tmp = stat(Path,&Stat);
  45. /* Stat now contains lots of info about the file,
  46. e.g. its size, though we are not interested in
  47. most of that info here */
  48. if (S_ISDIR(Stat.st_mode)) printf("*");
  49. printf("\n");
  50. }
  51. }
  52. return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement