Thread: Search in binary mode

  1. #1
    hyoutereda
    Guest

    Search in binary mode

    This program's purpose is to find the location of "AA BB CC 23 7F"(5 bytes) in a binary file.
    A file(argv[1]) is sure to have "AA BB CC 23 7F".
    However, this program sometimes don't work.
    Why?
    Then, please teach me better codes.

    ====== code (a part) ==========================

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

    FILE *fptr1;
    int b_index;
    int b[5];
    int lb1[5] = {0xAA, 0xBB, 0xCC, 0x23, 0x7F};
    long point1;

    fptr1 = fopen(argv[1], "rb");

    fseek(fptr1, 0L, SEEK_SET);
    for(b_index = 0; b_index < 5; b_index++)
    b[b_index] = getc(fptr1);

    do{
    for(b_index = 0; b_index < 4; b_index++)
    b[b_index] = b[b_index + 1];
    b[4] = getc(fptr1)
    }while(b[0] != lb1[0] || b[1] != lb1[1] || b[2] != lb1[2]
    || b[3] != lb1[3] || b[4] != lb1[4]);

    point1 = ftell(fptr1);
    printf("point1 = %X/n", point1);

    }

    =============================================

  2. #2
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Here some help:
    [list=1][*]Always check the number of arguments before you use them:
    Code:
    if(argc != 2)
    {
        printf("Usage: %s <filename>\n", argv[0]);
        return -1;
    }
    [*]Always check return values:
    Code:
    if((fptr1 = fopen(argv[1], "rb")) == NULL)
    {
        printf("Could not open file: %s\n", argv[1]);
        return -2;
    }
    [*]Check the return value of the getc function for EOF:
    Code:
    if((b[4] = getc(fptr1)) == EOF)
    {
        printf("Parrern not found\n");
        return -3;
    }
    [*]Return something (0) at the end of main.
    [*]Use code tags[/list=1]

    Cheers,
    Monster

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with binary search.
    By StateofMind in forum C Programming
    Replies: 6
    Last Post: 05-06-2009, 02:14 PM
  2. Performance issue!
    By maven in forum C Programming
    Replies: 42
    Last Post: 03-23-2009, 11:57 AM
  3. Tutorial review
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 03-22-2004, 09:40 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM