簡體   English   中英

從緩沖區讀取字節(字符)

[英]Read bytes (chars) from buffer

我正在使用Java編寫隱寫術程序。 但是我得到的建議是,我可以在C程序中更好地解決此任務。 我想嘗試一下,但是在C編程中我表現很差。 現在,我想讀取一個gif文件並找到用作圖像分隔符的字節( GIF格式0x2c )。

我嘗試編寫此程序:

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

有人可以給我建議如何修復我的回路嗎?

有人可以給我建議如何修復我的回路嗎?

選項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");
    }
}

與基於'for()'的答案類似,如果您只需要檢查特定的字節(0x2c),則可以使用while()簡單地執行以下操作(而不用擔心字節流中的null)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM