You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改XV6操作系统中ls命令以实现每行输出带行号

给XV6的ls命令添加行号的修改方案

要实现每行输出带行号,只需在ls函数中添加一个计数器变量,在输出文件/目录条目时同步递增并打印即可,具体修改如下:

修改后的完整代码

#include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"

char*
fmtname(char *path)
{
  static char buf[DIRSIZ+1];
  char *p;

  // Find first character after last slash.
  for(p=path+strlen(path); p >= path && *p != '/'; p--)
    ;
  p++;

  // Return blank-padded name.
  if(strlen(p) >= DIRSIZ)
    return p;
  memmove(buf, p, strlen(p));
  memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
  return buf;
}

void
ls(char *path)
{
  char buf[512], *p;
  int fd;
  struct dirent de;
  struct stat st;
  // 新增行号计数器
  int line_num = 0;

  if((fd = open(path, 0)) < 0){
    printf(2, "ls: cannot open %s\n", path);
    return;
  }

  if(fstat(fd, &st) < 0){
    printf(2, "ls: cannot stat %s\n", path);
    close(fd);
    return;
  }

  switch(st.type){
  case T_FILE:
    line_num = 1;
    // 输出时添加行号,格式为 [行号] 原内容
    printf(1, "%d %s %d %d %d\n", line_num, fmtname(path), st.type, st.ino, st.size);
    break;

  case T_DIR:
    if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
      printf(1, "ls: path too long\n");
      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, "ls: cannot stat %s\n", buf);
        continue;
      }
      // 每次输出前递增行号
      line_num++;
      printf(1, "%d %s %d %d %d\n", line_num, fmtname(buf), st.type, st.ino, st.size);
    }
    break;
  }
  close(fd);
}

int
main(int argc, char *argv[])
{
  int i;

  if(argc < 2){
    ls(".");
    exit();
  }
  for(i=1; i<argc; i++)
    ls(argv[i]);
  exit();
}

关键修改点

  • 在ls函数开头定义int line_num = 0作为行号计数器
  • 处理单个文件(T_FILE)时,直接将行号设为1,输出时把行号放在最前面
  • 处理目录(T_DIR)时,每次循环读取到有效条目后,先递增line_num再输出,确保每行对应唯一行号
  • 调整printf格式字符串,把行号作为第一个输出项

这样修改后,不管是查看单个文件还是目录下的多个条目,每行输出都会带有连续的行号,解决了只能显示总数的问题。

内容的提问来源于stack exchange,提问作者Abdullah Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:01:11