2012-01-16 68 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系列的所有评论也适用于此行。 (嘘:你需要检查错误。)

顺便说一句,逗号周围的间距不一致,请神灵用闪电击中你。所以在你的括号里面放置空格。