2012-01-16 66 views
1

下面是問題:我必須更改WAVE文件的標題,確切地說,我必須更改ChunkSize和SubChunk2Size。問題是,這些值使用4字節,但它seemt,使用的fwrite我覆蓋8個字節:C:編輯二進制文件

原:

RIFFđ WAVEfmt 

編輯:

RIFF(} } fmt 

代碼:

FILE *nova; 
nova=fopen ("nova.wav", "wb"); 

fseek (nova, 4, SEEK_SET); 
fwrite (&brojacC,4,1,nova); 
fseek (zvuk, 44, SEEK_SET); 
fwrite (&brojacCS2,4,1,nova); 

被編輯的文件WAVE被覆蓋。出錯了,因爲我從第4個字節開始寫了4個字節,而WAVE從第8個字節開始。

我希望我至少有一點清楚。這可以以其他方式完成嗎?

回答

3

那麼,根據我的man fopen輸出:

r  Open text file for reading. The stream is positioned at the 
      beginning of the file. 

    r+  Open for reading and writing. The stream is positioned at the 
      beginning of the file. 

    w  Truncate file to zero length or create text file for writing. 
      The stream is positioned at the beginning of the file. 

    w+  Open for reading and writing. The file is created if it does 
      not exist, otherwise it is truncated. The stream is positioned 
      at the beginning of the file. 

    a  Open for appending (writing at end of file). The file is cre‐ 
      ated if it does not exist. The stream is positioned at the end 
      of the file. 

    a+  Open for reading and appending (writing at end of file). The 
      file is created if it does not exist. The initial file position 
      for reading is at the beginning of the file, but output is 
      always appended to the end of the file. 

話雖這麼說,我肯定會去fopen("nova.wav", "r+b"),爲w似乎截斷文件,而你寫之前要讀書,一邊a追加到該文件的結尾,並且您想要重寫該文件的一部分。

2

此代碼在每行顯示至少有一個錯誤。

FILE *nova; 

它很容易被錯誤處理的權利,如果你做這樣的事情與openwrite,並且lseek而不是fopenfwritefseek

nova=fopen ("nova.wav", "wb"); 

第二個字符串應該是"r+b"而不是"wb"這樣你就不會截斷該文件。你需要檢查錯誤。

fseek (nova, 4, SEEK_SET); 

您需要檢查錯誤。

fwrite (&brojacC,4,1,nova); 

fwrite應始終與第二個參數1和第三個參數等於要被寫入的數據的大小調用;否則不可能從簡短的寫入中恢復。您需要檢查簡短的寫入和寫入錯誤。

你不顯示初始化brojacC,所以我不能評估你是否有任何字節順序或結構填充問題的代碼,但是我敢打賭,你做的。

fseek (zvuk, 44, SEEK_SET); 

這是作用在不相關的文件句柄zvuk而非nova。你需要檢查錯誤。

fwrite (&brojacCS2,4,1,nova); 

由於上一行的fseek呼叫施加到zvuk,這個寫入偏移量4 + 4 = 8,而不是偏移44之意。以前的fwrite系列的所有評論也適用於此行。 (噓:你需要檢查錯誤。)

順便說一句,逗號周圍的間距不一致,請神靈用閃電擊中你。所以在你的括號裏面放置空格。