fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <fcntl.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7.  
  8. int read(int fd, char *buf, int n);
  9. int write(int fd, char *buf, int n);
  10. int fstat(int fd, struct stat *st);
  11.  
  12. #define NAME_MAX 14
  13.  
  14. typedef struct {
  15. long ino;
  16. char name[NAME_MAX + 1];
  17. } Dirent;
  18.  
  19. typedef struct {
  20. int fd;
  21. Dirent d;
  22. } DIR;
  23.  
  24. DIR *opendir(char *);
  25. Dirent *readdir(DIR *);
  26. void closedir(DIR *);
  27.  
  28. void fsize(char *);
  29.  
  30. int main(int argc, char *argv[])
  31. {
  32. if (argc == 1)
  33. fsize(".");
  34. else
  35. while (--argc > 0)
  36. fsize(*++argv);
  37. return 0;
  38. }
  39.  
  40. void dirwalk(char *, void (*)(char *));
  41.  
  42. void fsize(char *name)
  43. {
  44. struct stat stbuf;
  45.  
  46. if (stat(name, &stbuf) == -1) {
  47. fprintf(stderr, "fsize: can't access %s\n", name);
  48. return;
  49. }
  50. if ((stbuf.st_mode & S_IFMT) == S_IFDIR) {
  51. dirwalk(name, fsize);
  52. }
  53. printf("%8ld %s\n", stbuf.st_size, name);
  54. }
  55.  
  56. #define MAX_PATH 1024
  57.  
  58. void dirwalk(char *dir, void (*fcn)(char *))
  59. {
  60. char name[MAX_PATH];
  61. Dirent *dp;
  62. DIR *dfd;
  63.  
  64. if ((dfd = opendir(dir)) == NULL) {
  65. fprintf(stderr, "dirwalk: can't open %s\n", dir);
  66. return;
  67. }
  68. while ((dp = readdir(dfd)) != NULL) {
  69. if (strcmp(dp->name, ".") == 0 || strcmp(dp->name, "..") == 0)
  70. continue;
  71. if (strlen(dir) + strlen(dp->name) + 2 > sizeof(name))
  72. fprintf(stderr, "dirwalk: name %s/%s too long\n", dir, dp->name);
  73. else {
  74. sprintf(name, "%s/%s", dir, dp->name);
  75. (*fcn)(name);
  76. }
  77. }
  78. closedir(dfd);
  79. }
  80.  
  81. DIR *opendir(char *dirname)
  82. {
  83. int fd;
  84. struct stat stbuf;
  85. DIR *dp;
  86.  
  87. if ((fd = open(dirname, O_RDONLY, 0)) == -1
  88. || fstat(fd, &stbuf) == -1
  89. || (stbuf.st_mode & S_IFMT) != S_IFDIR
  90. || (dp = malloc(sizeof(DIR))) == NULL)
  91. return NULL;
  92. dp->fd = fd;
  93. return dp;
  94. }
  95.  
  96. void closedir(DIR *dp)
  97. {
  98. if(dp) {
  99. close(dp->fd);
  100. free(dp);
  101. }
  102. }
  103. #define DIRSIZ 14
  104. struct direct
  105. {
  106. ino_t d_ino;
  107. char d_name[DIRSIZ];
  108. };
  109.  
  110. Dirent *readdir(DIR *dp)
  111. {
  112. struct direct dirbuf;
  113. static Dirent d;
  114.  
  115. while ((read(dp->fd, (char *) &dirbuf, sizeof(dirbuf))) != EOF) {
  116. if (dirbuf.d_ino == 0) {
  117. continue;
  118. }
  119. d.ino = dirbuf.d_ino;
  120. strncpy(d.name, dirbuf.d_name, DIRSIZ);
  121. d.name[DIRSIZ] = '\0';
  122. return &d;
  123. }
  124. printf("break");
  125. return NULL;
  126. }
Success #stdin #stdout 0s 1964KB
stdin
Standard input is empty
stdout
break    4096 .