2014-02-21 30 views
0

我已經爲此進行了廣泛搜索,現在花了4個小時,我希望有人能幫助我。Windows/TCC/C讀取隨機跳轉的二進制文件指針

我有一個簡單的程序來讀取一個二進制文件,大約2.7 MB。該程序使用tcc編譯器在Windows上編譯。我在各種高級語言(Pascal,Modula2,Matlab,PHP,Basic)方面經驗豐富,但對C來說是新手,並且懷疑這對於內存分配和變量被覆蓋有一些影響。

void main() 
{ 
    long int start_loc; 
    long int actual_loc; 
    int seek_result; 
    char file_to_process[]="d:/tmp/pfc/test.out"; 
    char read_int; 
    int spaces; 
    int read_result; 
    FILE *data_file; 
    //fpos_t position; 

    data_file=fopen(file_to_process,"r"); 

    if (data_file == NULL) { 
     printf("Error"); 
    } 

    start_loc = 1002; 

    printf("\n size of start_loc : %d",sizeof(start_loc)); 

    actual_loc = ftell(data_file); 
    printf("\nBEFORE location %d \n",actual_loc);   

    seek_result = fseek(data_file, start_loc, SEEK_SET); //move to start of search location in the file 

    actual_loc = ftell(data_file); 
    printf("\n AFTER seek location %d \n",actual_loc);   

    fread(&read_int, 1, 1, data_file); 

    actual_loc = ftell(data_file); 
    printf("\n AFTER read location %d \n",actual_loc);   
    printf("\n read result %x" ,*&read_int); 

    fread(&read_int, 1, 1, data_file); 
    actual_loc = ftell(data_file); 
    printf("\n AFTER read location %d \n",actual_loc);   
    printf("\n read result %x" ,*&read_int); 


    fclose(data_file); 
    return; 
} 

在上述我從文件中的位置1002讀出的實例 - 這個工作正常 - 其結果是:

size of start_loc : 4 
BEFORE location 0 

AFTER seek location 1002 

AFTER read location 1003 

read result 0 
AFTER read location 1004 
read result 3 

一切正常 - 由1個字符的文件指針前進每個字節讀。

問題出在某個值的起始位置,例如

start_loc = 16000

在這種情況下,文件指針例如命令後跳躍一個看似隨機的方式即讀取1個字節並且文件指針移動到19586.

size of start_loc : 4 
BEFORE location 0 

AFTER seek location 16000 

AFTER read location 19585 

read result 47 
AFTER read location 19586 

read result 0 

感謝您閱讀這篇文章!

+0

如果你不想說「這不是真正的隨機!」的話,避免說「隨機跳躍」。 – OJFord

+0

除非我誤解了你想要達到的目標,'size_of(start_loc)'並沒有按照你的想法去做。這給你'start_loc'類型(long int)的內存大小。 – OJFord

+0

是的,這是正確的 - 我很困惑發生了什麼我想檢查它真的是4個字節長,因此可以保持文件指針值高達2^32之後,因爲你說它什麼都不做 – rubusrubus

回答

1

您的文件在文本模式(r)和文本模式下打開,C++參考說明了關於ftell函數: 對於文本流,數值可能沒有意義,但仍可用於將位置恢復到相同在稍後使用fseek的位置(如果有使用ungetc仍然待讀取的字符放回,行爲是未定義的)。

所以你得到的似乎與文檔一致,不應該擔心你。

請注意,如果您想將其打開爲二進制文件,您應該在fopen模式下附加'b'。

+0

完美 - 添加一個「b」的開放字符串,它的工作原理... – rubusrubus