【发布时间】:2013-05-06 13:12:24
【问题描述】:
如何访问.wav文件的子块数据?
我一直在尝试将二进制数据(前 44 个字节)复制到一个结构变量(44 个字节的大小)。但是有一个问题:我确信我已经将二进制数据从文件input 复制到了一个名为hdr 的结构中。
但是当我尝试显示包含“RIFF”(字符数组)的 hdr.ChunkID 时,它不会打印“RIFF”。它什么也不打印。
#include <stdio.h>
#include <stdlib.h>
typedef struct FMT
{
char Subchunk1ID[4];
int Subchunk1Size;
short int AudioFormat;
short int NumChannels;
int SampleRate;
int ByteRate;
short int BlockAlign;
short int BitsPerSample;
} fmt;
typedef struct DATA
{
char Subchunk2ID[4];
int Subchunk2Size;
int Data[441000]; // 10 secs of garbage. he-he)
} data;
typedef struct header
{
char ChunkId[4];
int ChunkSize;
char Format[4];
fmt S1;
data S2;
} Header;
int main()
{
FILE *input = fopen("in.wav", "rb");
FILE *output = fopen("out.wav", "wb");
unsigned char buf[64];
Header hdr;
if(input == NULL)
{
printf("Unable to open wave file\n");
exit(EXIT_FAILURE);
}
fread(&buf, sizeof(char), 64, input);
fwrite(&buf, sizeof(char), 64, output);
fread(&hdr, sizeof(char), 64, output);
printf("\n>>> %s", hdr.ChunkId); /* Here it is. */
fclose(input);
fclose(output);
return 0;
}
不明白哪里出了问题。
【问题讨论】:
-
如果你需要读44字节,你为什么读64?你将如何处理你读取的额外 20 个字节?
-
我有一个程序可以显示前 64 个字节并解释它们...例如前 4 个字节 ---> "RIFF" 等等。
-
对于其余数据,您可能需要检查(例如
sizeof(Header))您拥有的结构是否未被填充。如果来自sizeof的值与应有的值不同,则需要告诉编译器不应填充结构。
标签: c file struct binary-data