2014-11-06 61 views
-1
int main() 
{ 

long int length = 0; /*file byte length*/ 
int index; 
FILE *myFile; 

    myFile = fopen("test file", "r+b"); 

if(!myFile) 
{ 
    printf("Error, unable to open file"); 
    return 1; 
} 
else 
{ 
    /*Lets find the total bytes in the file*/ 
    fseek(myFile, 0, SEEK_END); /*Seeks end for length*/ 
    length = ftell(myFile); 
    fseek(myFile,0, SEEK_SET); /*seeks beginning for reset*/ 
    printf("Total file bytes is %d\n",length); 
    unsigned char buffer[32]; /*reading into buffer 4 bytes, 32 bits*/ 
    size_t bytes_read = 0; 

    for(index = 0; index < 30; index++) /*30 is just a testing value*/ 
    { 
    bytes_read = fread(&buffer,4,1,myFile); /*Read 4 bytes at a time*/ 

    printf("Bytes read: %i", bytes_read); 
    printf("%s\n",buffer); 
    } 

} 




    fclose(myFile); 
    return 0; 
} 

修改之前,我繼續下去,是的,這是不是一個高效的程序,將創造大量的開銷......二進制I/O,查找特定字節的文件

我讀每次4個字節,但不知道如何讀取實際的二進制0和1或十六進制值,以便比較和修改十六進制或二進制值。我將如何去閱讀在這裏打開的程序的十六進制/二進制值?

+0

我不知道我明白你在說什麼。從技術上講,你唯一可以閱讀的是1和0。無論是十六進制,十進制還是八進制,基本上只是您讀到的內容的一種表示。所以,作爲示例,我可以比較255 == 0xFF。底層的1和0是相同的 – 2014-11-06 21:00:01

+0

...只是一個友好的FYI,你對你的「緩衝區」聲明的評論是不正確的。你實際上是宣佈32字節,而不是32位 – 2014-11-06 21:00:56

+0

@Don Shankin,我想我是每個字節的個別位給我32位,但現在我知道 – ShadowX 2014-11-06 21:05:10

回答

0

如果你想看到印刷爲十六進制字節的二進制文件值,請嘗試以下:

您的緩衝區的聲明更改爲:

uint32_t buffer; 

和你的printf到:

printf("0x%0X\n", buffer); 

使用uint32_t類型將保持您的fread符合您的緩衝區在整數可能不是32位的機器上。要使用它,你可能需要

#include <stdint.h> 

使用您的fread,這將讀取你的文件4個字節爲一個4字節的類型。這將被打印爲十六進制值。

0

您的緩衝區大小爲32個字節;數組參數根據單位設置大小。在大多數系統中,無符號字符是1個字節(8位),因此您的緩衝區大小爲8 * 32位。

就目前而言,您的緩衝區包含4個字節的文件,之後包含28個空字節。

你可以在那些前4個字節像你這樣的操作會在一個陣列中的任何值,前

if (0x2 == buffer[0]) 
{ 
    printf("I found a 2 in hex!"); 
} 
相關問題