开发者

Reading binary files in C, on UNIX systems (Ubuntu 10.10)

开发者 https://www.devze.com 2023-01-25 06:05 出处:网络
this is my first time programming in C, and on a UNIX system.I am trying to do something fairly simple.I have a binary file that is an image of a Compact Flash camera card, and consists of a few JPG i

this is my first time programming in C, and on a UNIX system. I am trying to do something fairly simple. I have a binary file that is an image of a Compact Flash camera card, and consists of a few JPG images. I am trying to read through the file, find the byte sequence corresponding to FF D8 FF E0, or FF D8 FF E1, the signifiers of the beginning of a JPG file, then writing everything between that signifier and the next to a new jpg file.

At the moment I am just trying to get my computer to print out the file as is, by reading it in 512 size blocks, the stated size of the blocks in the original file system. I have the following code:

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main (int argc, char *argv[])
{
    FILE * raw;
    FILE * currentimage;
    char buf[512];
    char beg1[32] = "11111111110110001111111111100001";
    char beg2[32] = "11111111110110001111111111100000";

    raw = fopen("card.raw", "rb");

    while((fread(buf, sizeof(raw), 512, raw) > 0))
    {
        printf(buf);
        printf("\n");

    }
}

It just prints out the file formatted into what I presume is ASCII, so it looks like a bunch of gobbledegook. How can I get this data formatted to either binary 1's and 0's or, even better, hex 0-F's?

Any help would be much 开发者_运维百科appreciated.

P.S. beg1 and beg2 correspond to the binary values of the hex values I am looking for, but they are not really relevant to the rest of the code I have at the moment.


Instead of printf(buf); you would need to loop through each byte and do printf("%02x ", byte). Take a look at the source of hexdump here:

  • http://qa.coreboot.org/docs/doxygen/hexdump_8c_source.html


You should read up on what printf() does, as in NO PROGRAMMING LANGUAGE that I know, should you EVER use data as the first argument to printf. The first argument should be a template, which the way you used it should be "%s". To see hex output, replace your loop with this:

int size;
while((size = (fread(buf, sizeof(raw), 512, raw)) > 0))
{
    for (int i = 0; i < size; i++)
    {
        printf("%2X", buf[i]);
    }
    printf("\n");

}

To answer your question about comparision in C before printing: The numerical data is right there in buf -- buf[i] is an char from -127 to 128 that contains the value. If you want to look at its hex representation, you can do:

 sprintf(some_other_buffer, "%2X", buf[i]);

Then you can perform string manipulation on some_other_buffer, knowing it's a 2 character string.

0

精彩评论

暂无评论...
验证码 换一张
取 消