如图所示,本来是一个长度为4的字符数组,用%c手动一个一个输出是正常显示,但是用%s直接输出这个字符数组就出现输出位数并不是4,这是什么原因呢?是这个字符数组的后面没有带上0吗?遇到这种情况有什么简便的方法快速输出字符串吗?(万一有个长度几百的字符数组要输出难道我得手动一个一个用字符数组成员拼接吗?)
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
typedef struct WAV_header {
char ChunkID[4]; /* "RIFF" */
uint32_t ChunkSize; /* 36 + Subchunk2Size */
char Format[4]; /* "WAVE" */
/* sub-chunk "fmt" */
char Subchunk1ID[4]; /* "fmt " */
uint32_t Subchunk1Size; /* 16 for PCM */
uint16_t AudioFormat; /* PCM = 1*/
uint16_t NumChannels; /* Mono = 1, Stereo = 2, etc. */
uint32_t SampleRate; /* 8000, 44100, etc. */
uint32_t ByteRate; /* = SampleRate * NumChannels * BitsPerSample/8 */
uint16_t BlockAlign; /* = NumChannels * BitsPerSample/8 */
uint16_t BitsPerSample; /* 8bits, 16bits, etc. */
/* sub-chunk "data" */
char Subchunk2ID[4]; /* "data" */
uint32_t Subchunk2Size; /* data size */
} Wav_header_t;
typedef struct WAV_block_header {
char blockID[4]; /* "data" */
uint32_t blockSize; /* data size */
} Wav_block_header_t;
int main()
{
FILE *fp = NULL;
Wav_header_t header;
Wav_block_header_t block_header;
fp = fopen("test.wav", "rb");
if (!fp) {
printf("can't open audio file\n");
exit(1);
}
fread(&header, 1, sizeof(Wav_header_t), fp);
// printf("length:%d(10),0x%x, \n\n", sizeof(struct WAV_Format), sizeof(struct WAV_Format)); // 44
printf("ChunkID \t%c%c%c%c\n", header.ChunkID[0], header.ChunkID[1], header.ChunkID[2], header.ChunkID[3]);
printf("ChunkSize \t%d\n", header.ChunkSize);
printf("Format \t%s\n", header.Format);
printf("Subchunk1ID \t%x\n", header.Subchunk1ID);
printf("Subchunk1Size \t%d\n", header.Subchunk1Size);
printf("AudioFormat \t%d\n", header.AudioFormat);
printf("NumChannels \t%d\n", header.NumChannels);
printf("SampleRate \t%d\n", header.SampleRate);
printf("ByteRate \t%d\n", header.ByteRate);
printf("BlockAlign \t%d\n", header.BlockAlign);
printf("BitsPerSample \t%d\n", header.BitsPerSample);
printf("Subchunk2ID \t%s\n", header.Subchunk2ID);
printf("Subchunk2Size \t%d\n", header.Subchunk2Size);
printf("\n");
fread(&block_header, 1, sizeof(Wav_block_header_t), fp);
printf("blockID \t%s\n", block_header.blockID);
printf("blockSize \t%d\n", block_header.blockSize);
}
欧阳克2017-06-12 09:26:55
C语言的字符串结尾结束用' '表示
这个数组ChunkID[4]应该申明为ChunkID[5],然后填值时,在最后结束加上' ',
在这个例子里是ChunkID[4] = ' ',就可以用"%s"输出字符串了.