2017-01-23 89 views
0

六角這是我當前的代碼:閱讀文件在C

#include "fileread.h" 

typedef struct 
{ 
    char Key[50]; 
    int KeyLen; 
} KeyStorage; 

eKeyFileRes GetNewKeyFile( char *path, UINT64 fileName, KeyStorage *keyStorage) 
{ 
    char sbuf[1024]; 
    FILE* file; 
    sprintf (sbuf, "%s\\%llu.dat", path, fileName); 
    file=fopen(sbuf, "r"); 

    if(file == NULL) 
    { 
     return KeyFileRes_NoKeyFound; 
    } 
    else 
    { 
     fread(keyStorage->Key,1,50, file); 
     fseek(file, 0L, SEEK_END); 
     keyStorage->KeyLen = ftell(file); 
    } 
    fclose(file); 
    return KeyFileRes_NewKeyFound; 
} 

它工作正常,但問題是,我需要讀取該文件,然後保存在buffer(keyStorage->key)但在十六進制。

這裏是一個文件例如:

6B53E460E5D944A1200BE51A91588B50D3E887081E5DA5F90ADD71CF88D83A3C469EDB56E6FD526A4946B781257FFC950367 
+0

所以,如果我理解你想被存儲在'key'是0x6b前4個字節, 0x53,0xe4,0x60,給出您的問題中的文件示例。如我錯了請糾正我。 –

+0

或者你想要一個由100個字符組成的字符串+ null終止符? – stark

+0

@MichaelWalz是的,你是對的 –

回答

0

這應該給你一個想法:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() {  
    char string[] = "6B53E460E5D9"; // NUL terminated sample string 
    int length = strlen(string);  // get length of sample string 

    for (int i = 0; i < length; i += 2) 
    { 
    char tmp[3];  
    tmp[0] = string[i];        // copy 2 chars 
    tmp[1] = string[i+1];       // " 
    tmp[2] = 0;          // put the NUL terminator 
    int value = strtol(tmp, NULL, 16);    // transform hex string to value 
    printf("%d %02x %d\n", i/2, value, value); // show results 
    } 
}