我正在尝试更改.wav文件头中与文件大小相对应的字节,即第4个和第40个字节。目前,我正在将整个标头复制到缓冲区,尝试在那里编辑它,然后将其写入目标文件,但它似乎不起作用。
int main(int argc, char * argv []){
int delay = atoi(argv[1]);
FILE * source = fopen(argv[2], "rb");
FILE * destination = fopen(argv[3], "wb");
void * header = malloc(44); // size of a wav file header
fread(header, sizeof(header), 1, source);
// my attempt at changing the 4nd and 40th bytes
sizeptr1 = (unsigned int *)(header + 4);
sizeptr2 = (unsigned int *)(header + 40);
*sizeptr1 = *sizeptr1 + delay;
*sizeptr2 = *sizeptr2 + delay
fwrite(header, sizeof(header), 1, destination);
return 0;
}
更改这些字节并将新标头写入输出文件的最有效方法是什么?
答案 0 :(得分:1)
如果您确定要更改哪些字节,则字节数组最简单。例如,第4个字节位于buffer[3]
。
#include <stdio.h>
#include <stdlib.h>
#define BUFFSIZE 1024
#define HEADSIZE 44
int main(int argc, char * argv []) {
int delay;
size_t bytes;
FILE * source = NULL;
FILE * destination = NULL;
unsigned char buffer[BUFFSIZE];
if (argc < 4) return 0; // check enough args
delay = atoi(argv[1]);
if (NULL == (source = fopen(argv[2], "rb")))
return 0;
if (NULL == (destination = fopen(argv[3], "wb")))
return 0;
// copy & alter buffer
if (HEADSIZE != fread(buffer, 1, HEADSIZE, source))
return 0;
buffer[4] = delay;
buffer[40] = delay;
if (HEADSIZE != fwrite(buffer, 1, HEADSIZE, destination))
return 0;
// copy rest of file
while ((bytes = fread(buffer, 1, BUFFSIZE, source)) != 0) {
if (bytes != fwrite(buffer, 1, bytes, destination))
return 0;
}
if (0 == fclose(destination))
printf("Success\n");
fclose (source);
return 0;
}
答案 1 :(得分:0)
这是编辑文件中字节的一种方法,检查它是否适合您。
int
ChangeHeaderByte(
const char* fileName,
unsigned int pos[],
unsigned int val[],
unsigned int size
)
{
unsigned int i = 0;
unsigned int temp = 0;
FILE * fileHandle = fopen(fileName, "r+");
if (fileHandle == 0) {
fprintf(stderr,"Error: %s : %d : Failed to open file ' %s '\n",
__func__,__LINE__,fileName);
return (1);
}
for ( i = 0; i < size ; ++i )
{
if ( fseek(fileHandle, pos[i] - (unsigned int)1, SEEK_SET) == 0 )
{
if ( fread(&temp,sizeof(unsigned int),1,fileHandle) == 1 )
{
if ( fseek(fileHandle, pos[i] - (unsigned int)1 , SEEK_SET) == 0 )
{
val[i] += temp;
fwrite(&val[i], sizeof(unsigned int), 1, fileHandle);
}
else
{
fprintf(stderr,"Error: %s : %d : fseek() failed on file ' %s '\n",
__func__,__LINE__,fileName);
return (1);
}
}
else
{
fprintf(stderr,"Error: %s : %d : fread() failed on file ' %s '\n",
__func__,__LINE__,fileName);
return (1);
}
} else {
fprintf(stderr,"Error: %s : %d : fseek() failed on file ' %s '\n",
__func__,__LINE__,fileName);
return (1);
}
}
fclose(fileHandle);
return (0);
}
int main(void)
{
const unsigned int size = 2;
char fileName[] = "C:\\Users\\sridhar\\test\\test.wav";
unsigned int pos[2] = { 4 , 40 };
unsigned int val[2] = { 123456, 123456 };
ChangeHeaderByte(fileName,pos,val,size);
return 0;
}