Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read bytes (chars) from buffer

I'm working on steganography program in Java. But I got advice that I be able to resolve this task better in C program. I would like to try it, but I'm pretty bad in C programing. For now I would like to read one gif file and find byte which is used as image separator (0x2c from GIF format).

I tried to write this program:

int main(int argc, char *argv[])
{
    FILE *fileptr;
    char *buffer;
    long filelen = 0;

    fileptr = fopen("D:/test.gif", "rb");  // Open the file in binary mode
    fseek(fileptr, 0, SEEK_END);          // Jump to the end of the file
    filelen = ftell(fileptr);             // Get the current byte offset in the file
    rewind(fileptr);                      // Jump back to the beginning of the file

    buffer = (char *)malloc((filelen+1)*sizeof(char)); // Enough memory for file + \0
    fread(buffer, filelen, 1, fileptr); // Read in the entire file
    fclose(fileptr); // Close the file

    int i = 0;
    for(i = 0; buffer[ i ]; i++)
    {
        if(buffer[i] == 0x2c)
        {
            printf("Next image");
        }
    }


    return 0;
}

Could someone give me advice how to repair my loop?

like image 965
Sk1X1 Avatar asked May 01 '26 03:05

Sk1X1


1 Answers

Could someone give me advice how to repair my loop?

Option 1: Don't depend on the terminating null character.

for(i = 0; i < filelen; i++)
{
    if(buffer[i] == 0x2c)
    {
        printf("Next image");
    }
}

Option 2: Add the terminating null character before relying on it. This is potentially unreliable since you are reading a binary file that could have embedded null characters in it.

buffer[filelen] = '\0';
for(i = 0; buffer[ i ]; i++)
{
    if(buffer[i] == 0x2c)
    {
        printf("Next image");
    }
}
like image 164
R Sahu Avatar answered May 02 '26 21:05

R Sahu