making tree function in xv6



如果您不知道树是在终端上列出目录的,我想在xv6中创建tree命令。我知道这对你来说可能很容易,但到目前为止代码是

#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
#include "fs.h"
#include "file.h"
int
main(int argc, char *argv[])
{
if(argc < 2){
printf(2, "Usage: tree [path]...n");
exit();
}
tree(argv[1]);

int fd = open(argv[1],O_RDONLY);
if(fd<0)
return -1;
struct dirent dir;
while(read(fd,&dir,sizeof(dir))!=0){
printf(1,"|_ %d,%d",dir.name,dir.inum);
//struct stat *st;
struct inode ip;
ip= getinode(dir.inum);
if(ip.type==T_DIR){
int i;
for(i=0;i<NDIRECT;i++ ){
uint add=ip.addrs[i];
printf(1,"%d",add);
}
}
}
return 0;
}

它在终端上给了我很多错误,第一个是file.h:17:20: error: field ‘lock’ has incomplete type struct sleeplock lock; // protects everything below here ^~~~

我正在搜索sleeplock,但代码中没有类似的内容。代码出了什么问题?感谢您的帮助

不能在用户代码中使用内核标头(如file.h(。要在代码中使用内核函数,必须使用系统调用。

为了实现您想要的,您可以从ls函数开始,并使其递归。

一个快速制作的例子:

  • 我在ls函数中添加了一个参数来显示爬行的深度
  • 并在除...这两个第一目录元素之外的每个目录元素上调用自己


void
ls(char *path, int decal)
{
char buf[512], *p;
int fd, i, skip = 2;
struct dirent de;
struct stat st;
if((fd = open(path, 0)) < 0){
printf(2, "tree: cannot open %sn", path);
return;
}
if(fstat(fd, &st) < 0){
printf(2, "tree: cannot stat %sn", path);
close(fd);
return;
}
switch(st.type){
case T_FILE:
for (i = 0; i < decal; i++)
printf(1, " ");
printf(1, "%s %d %d %dn", fmtname(path), st.type, st.ino, st.size);
break;
case T_DIR:
if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
printf(1, "tree: path too longn");
break;
}
strcpy(buf, path);
p = buf+strlen(buf);
*p++ = '/';
while(read(fd, &de, sizeof(de)) == sizeof(de)){
if(de.inum == 0)
continue;
memmove(p, de.name, DIRSIZ);
p[DIRSIZ] = 0;
if(stat(buf, &st) < 0){
printf(1, "tree: cannot stat %sn", buf);
continue;
}
for (i = 0; i < decal; i++)
printf(1, " ");
printf(1, "%s %d %d %dn", fmtname(buf), st.type, st.ino, st.size);
if (skip)
skip--;
else 
ls(buf, decal+1);
}
break;
}
close(fd);
}

最新更新