ls.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "types.h"
  2. #include "stat.h"
  3. #include "user.h"
  4. #include "fs.h"
  5. char*
  6. fmtname(char *path)
  7. {
  8. static char buf[DIRSIZ+1];
  9. char *p;
  10. // Find first character after last slash.
  11. for(p=path+strlen(path); p >= path && *p != '/'; p--)
  12. ;
  13. p++;
  14. // Return blank-padded name.
  15. if(strlen(p) >= DIRSIZ)
  16. return p;
  17. memmove(buf, p, strlen(p));
  18. memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
  19. return buf;
  20. }
  21. void
  22. ls(char *path)
  23. {
  24. char buf[512], *p;
  25. int fd;
  26. struct dirent de;
  27. struct stat st;
  28. if((fd = open(path, 0)) < 0){
  29. printf(2, "ls: cannot open %s\n", path);
  30. return;
  31. }
  32. if(fstat(fd, &st) < 0){
  33. printf(2, "ls: cannot stat %s\n", path);
  34. close(fd);
  35. return;
  36. }
  37. switch(st.type){
  38. case T_FILE:
  39. printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size);
  40. break;
  41. case T_DIR:
  42. if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
  43. printf(1, "ls: path too long\n");
  44. break;
  45. }
  46. strcpy(buf, path);
  47. p = buf+strlen(buf);
  48. *p++ = '/';
  49. while(read(fd, &de, sizeof(de)) == sizeof(de)){
  50. if(de.inum == 0)
  51. continue;
  52. memmove(p, de.name, DIRSIZ);
  53. p[DIRSIZ] = 0;
  54. if(stat(buf, &st) < 0){
  55. printf(1, "ls: cannot stat %s\n", buf);
  56. continue;
  57. }
  58. printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
  59. }
  60. break;
  61. }
  62. close(fd);
  63. }
  64. int
  65. main(int argc, char *argv[])
  66. {
  67. int i;
  68. if(argc < 2){
  69. ls(".");
  70. exit();
  71. }
  72. for(i=1; i<argc; i++)
  73. ls(argv[i]);
  74. exit();
  75. }