与hexdump相比,C read()产生错误的字节顺序?

时间:2016-03-01 09:59:29

标签: c endianness

我对C编程很陌生,最近我试图在我的x86 Linux系统上使用C语言中的一些低级I / O函数,以便更好地理解内部进程。作为一个练习,我决定编写一个小程序,它应该从文件中读取数据并在控制台上生成类似hexdump的输出。我的程序读取文件的前512个字节,并将缓冲区传递给产生输出的函数。

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

#define BYTES 512

void printout(unsigned char *data){
        for (int i=0; i < BYTES; i++){
                if (i == 0 || i % 16 == 0) printf("%07x ",i);
                printf("%02x", data[i]);
                if (i % 2) 
                        printf(" ");
                if ((i + 1) % 16 == 0)
                        printf("\n");
        }
        printf("%07x\n",BYTES);
        return;
}

int main(int argc, char **argv){
        unsigned char data[BYTES];
        char *f;
        int fd;

        if(argv[1]==NULL){
                fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
                return EXIT_FAILURE;
        }

        f = argv[1];
        fd=open(f, O_RDONLY);

        if(fd == -1){
                fprintf(stderr, "Error: Could not open file %s\n", f);
                return EXIT_FAILURE;
        }

        read(fd, data, BYTES);
        printout(data);

        close(fd);
        return EXIT_SUCCESS;
}

不幸的是,当我将输出与hexdump或od进行比较时,似乎我的程序恢复了字节顺序。

$ myprogram /dev/sda |head -1
0000000 eb63 9000 0000 0000 0000 0000 0000 0000
$ hexdump /dev/sda |head -1
0000000 63eb 0090 0000 0000 0000 0000 0000 0000

由于od -x --endian = little产生与hexdump相同的结果,我确信问题可以在我的代码中找到,但我不知道。如果有人能够向我解释为什么会发生这种情况以及我分别缺少什么,我将不胜感激。我在网上搜索过但到目前为止找不到任何有用的东西。

感谢您的帮助!

问候,Dirk

0 个答案:

没有答案
相关问题