简体   繁体   English

在 xv6 中读取 hex 文件

[英]hex file reading in xv6

I am trying to modify this xv6 c file into a hex viewer.我正在尝试将此 xv6 c 文件修改为十六进制查看器。 I tried to utilize printf(%02X) but to no avail.我尝试使用 printf(%02X) 但无济于事。 I tried doing different combinations of placement for the printf(%02X) but it will either not print hex or just print "%02X" at the end of the file view.我尝试对 printf(%02X) 进行不同的放置组合,但它要么不打印十六进制,要么只在文件视图末尾打印“%02X”。 For the printf functionality, it specifies these input arguments: Print to the given fd.对于 printf 功能,它指定这些输入 arguments:打印到给定的 fd。 Only understands %d, %x, %p, %s.只理解 %d、%x、%p、%s。 void printf(int fd, const char *fmt, ...) Here is the code I am working with: void printf(int fd, const char *fmt, ...)这是我正在使用的代码:

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

char buf[512];

void
hex(int fd)
{
  int n;

  while((n = read(fd, buf, sizeof(buf))) > 0) {
   if (write(1, buf, n) != n) {
     printf(1, "hex: write error\n");
     exit();
     }
    printf(n,"%02X");
   } 
   if(n < 0){
     printf(1, "hex: read error\n");
     exit();
   }

}

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

  if(argc <= 1){
    hex(0);
    exit();
  }

  for(i = 1; i < argc; i++){
    if((fd = open(argv[i], 0)) < 0){
      printf(1, "hex: cannot open\n", argv[i]);
      exit();
    }
    hex(fd);
    close(fd);
  }
  exit();
}

As you found yourself, in xv6, printf is very limited and you can't use %02x modifier.正如您发现的那样,在 xv6 中, printf非常有限,您不能使用%02x修饰符。 You have to restrict your self to %x (or you can extend the printf function, but it's an exercise beyond what is asked to you.您必须将自己限制在%x (或者您可以扩展printf function,但这是一项超出要求的练习。

For each character, you have to call printf(1, "%x ", the_character);对于每个字符,您必须调用printf(1, "%x ", the_character); For characters for 0x10 to 0xFF , it will print two character, for characters under 0x10 , you have to add the extra 0 .对于0x100xFF的字符,它将打印两个字符,对于0x10以下的字符,您必须添加额外的0

-- To print char by char, you need a for loop on the buffer you got after the read call. -- 要逐个字符打印,您需要在read调用后获得的缓冲区上进行for循环。 Add some space and LF to improve visibility and you're done.添加一些空间和 LF 以提高可见性,您就完成了。

void hex(int fd)
{
  char buf[16];

  int n, i;

  while((n = read(fd, buf, sizeof(buf))) > 0) {
    for (i = 0; i < n; ++i) {
        if (buf[i] < 0x10) {
            printf(1, "0");
        }
        printf(1,"%x ", buf[i]);
    }
    printf(1, "\n");
   } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM