2013-08-17 51 views
0

我創建了一個4000塊的文件,塊大小爲4096字節。 現在我想操作單個塊並再次讀取它們而不更改文件的大小。 其實我想寫出另一個文件的塊到我創建的文件中的特定塊。 因此我打開文件中binarymode這樣的:C以二進制模式讀取/寫入文件

FILE * storeFile=fopen(targetFile, "wb"); // this one I created before 
FILE * sourceFILE=fopen(sourceFile,"rb"); 

現在我想讀的東西的指針

char * ptr=malloc(4096); 
... 
for(i=0; i<blocks_needed; i++) 
{ 
    fread(ptr,4096,1,sourceFile); 
    // now I am going to the position of the blocks I want to write to 
    fseek(storeFile,freeBlocks[i]*4096,SEEK_SET); 
    // and now I am writing it to the File I created before 
    fwrite(ptr,4096,1,storeFile); 
... 
} 

出於某種原因,我改變之前創建的文件它的大小,變成了我想寫入的文件的副本。

我在做什麼錯?

預先感謝您!

回答

3

fopen手冊頁:

``w'' Truncate to zero length or create text file for writing. The stream is posi- 
     tioned at the beginning of the file. 

你擦除每次你打開它的目標文件。你可能有興趣在aa+

``a'' Open for writing. The file is created if it does not exist. The stream is posi- 
     tioned at the end of the file. Subsequent writes to the file will always end up 
     at the then current end of file, irrespective of any intervening fseek(3) or sim- 
     ilar. 

``a+'' Open for reading and writing. The file is created if it does not exist. The 
     stream is positioned at the end of the file. Subsequent writes to the file will 
     always end up at the then current end of file, irrespective of any intervening 
     fseek(3) or similar. 
+0

一個滑稽的錯誤。用於讀取的'r',用於寫入的'w'(讀取*覆蓋*)和用於追加的'a'。 –

+0

謝謝你的回答我試試這個。 – SevenOfNine

0

的問題是,你需要尋求將一些字節從文件開始的偏移量。 由於塊的長度爲4096,所以偏移將是(長)i * 4096;

我認爲你正在尋找錯誤的位置,因爲freeBlocks [i]可能是一個地址。

+0

爲什麼(長)我* 4096?我也在循環結束時執行倒帶(文件)。這應該讓我回到起點。你能解釋一下嗎? – SevenOfNine