2016-01-27 12 views
0

我有一些問題與我的代碼,我不知道明白。我讀了一個文件(你可以嘗試使用任何文件)來獲取十六進制值。我試圖找到某些十六進制值並對其進行更改 - 這很有用,但它比應該更晚。例如:改變字符的鄰居

0xAA 0xAB 0xAC 0xAD 0XAE ... 0XCD 0xCE 

我想更改0xAB,但我的代碼更改0XCD。不知道爲什麼會發生這種情況,但也許我錯了。還有一種方法可以自動獲取文件長度?我只是把一個緩衝區,是該文件的一部分,但我想獲得真正的長度。

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

#define FLEN 512 

int convert_to_hex(char c); 

int main(int argc, char *argv[]) { 

    char c; 
    int i = 0; 

    FILE *fp = fopen(argv[1],"rb"); 

    for(i = 0; i < FLEN; i++) { 
     c = convert_to_hex(fgetc(fp)); 
     printf("%02x ", c); 
    } 
    printf("\n"); 
} 

int convert_to_hex(char c) 
{ 
    char hexVal[3]; 
    sprintf(hexVal, "%02X", 0x69); 

    if(strncmp(&c, hexVal, 2) == 1) { 
     printf(">> %s ", hexVal); // indicate where it change (late) 
     return c + 1; 
    } 
    return c; 
} 
+0

應該是字符hexVal [4],而不是hexVal [3],一個空終止字符 – novice

+0

http://stackoverflow.com/questions/238603/how-can-i-get-a-files-size -in-c - 在C++中獲取文件長度 – novice

+0

@novice - 是的,它仍然具有相同的行爲。感謝其他鏈接 –

回答

1

這是一個錯誤。

if(strncmp(&c, hexVal, 2) == 1) { 

strncmp()的第一個參數被認爲是一個以NULL結尾的字符串。但是,您將它傳遞給單個字符的指針。我不明白你的convert_to_hex()函數試圖完成什麼,否則我可以建議一個替代方案。

要確定文件長度,只需檢查fgetc()的返回值是否爲EOFEOF是一個特殊的值,表明你在文件的末尾。

int c = fgetc(fp); // declare an int to hold the return value from fgetc() 
int fileLength = 0; // keep track of the file length 
while(c != EOF) { // repeat while we're not at the end of the file 
    c = convert_to_hex(c); 
    printf("%02x ", c); 
    c = fgetc(fp); // get the next character 
    fileLength++; // increment fileLength for each character of the file. 
} 
// we're done! - fileLength now holds the length of the file 
1

事實證明,答案很簡單,改變了我的convert_hex到:

int convert_to_hex(char c) 
{ 
    if (c == 0x69) { 
     c = c + 1; 
    } 
    return c; 
} 

this answer就是解決了這個問題對我來說。謝謝其他人。