【问题标题】:Read bytes (chars) from buffer从缓冲区读取字节(字符)
【发布时间】:2015-07-26 11:16:04
【问题描述】:

我正在研究 Java 中的隐写术程序。但我得到的建议是我能够在 C 程序中更好地解决这个任务。我想尝试一下,但我在 C 编程方面很糟糕。现在我想读取一个gif 文件并找到用作图像分隔符的字节(0x2c 来自GIF format)。

我试着写这个程序:

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;
}

有人可以给我建议如何修复我的循环吗?

【问题讨论】:

  • 您看到的问题是什么。 0x2C0x00 也可以是图像中的数据字节。
  • 你的循环是怎么坏的?事实上,它会在第一次buffer[i] 为零时退出;这就是你想要的吗?
  • 你可以用for(i = 0; i<filelen; i++)
  • @Politank-Z 在我发布的链接中写道,0x2c 是用作图像分隔符的字节。我如何识别它是图像分隔符还是普通字节?
  • 我不明白 - 您已经在循环内测试 buffer[i] == 0x2c。从您所说的来看,这似乎是您区分图像分隔符和普通字节的方式。

标签: c steganography


【解决方案1】:

有人可以给我建议如何修复我的循环吗?

选项 1:不要依赖终止空字符。

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

选项 2:在依赖它之前添加终止空字符。这可能不可靠,因为您正在读取的二进制文件中可能嵌入了空字符。

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

【讨论】:

  • 应该是buffer[filelen-1]=\0; ?
  • @ryyker, filelen 是对的,因为他分配了filelen+1 个字符。
【解决方案2】:

类似于基于 'for()' 的答案,如果您只需要检查特定字节 (0x2c),您可以简单地执行以下操作(不用担心字节流中的 null),使用 while ()。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多