交替读取为char*和wchar_t*
Alternate reading as char* and wchar_t*
我正试图编写一个解析ID3标签的程序,用于教育目的(因此,请在我尝试学习的过程中进行深入解释)。到目前为止,我已经取得了巨大的成功,但仍然存在编码问题。
读取mp3文件时,所有文本的默认编码为ISO-8859-1。所有报头信息(帧ID等)都可以在该编码中读取。
我就是这样做的:
ifstream mp3File("../myfile.mp3");
mp3File.read(mp3Header, 10); // char mp3Header[10];
// .... Parsing the header
// After reading the main header, we get into the individual frames.
// Read the first 10 bytes from buffer, get size and then read data
char encoding[1];
while(1){
char frameHeader[10] = {0};
mp3File.read(frameHeader, 10);
ID3Frame frame(frameHeader); // Parses frameHeader
if (frame.frameId[0] == 'T'){ // Text Information Frame
mp3File.read(encoding, 1); // Get encoding
if (encoding[0] == 1){
// We're dealing with UCS-2 encoded Unicode with BOM
char data[frame.size];
mp3File.read(data, frame.size);
}
}
}
这是错误的代码,因为data
是char*
,它的内部应该是这样的(将不可显示的字符转换为int):
char = [0xFF, 0xFE, C, 0, r, 0, a, 0, z, 0, y, 0]
两个问题:
- 前两个字节是什么?-回答
- 如何从已打开的文件中读取wchar_t?然后继续阅读剩下的内容
编辑澄清:我不确定这是否是正确的方法,但基本上我想做的是。。将前11个字节读取到char数组(标头+编码),然后将下12个字节读取至wchar_t数组(歌曲名称),然后再将下10个字节读取为char数组(下一个标头)。这可能吗?
我找到了一个不错的解决方案:创建一个新的wchar_t缓冲区,并将char数组中的字符成对添加。
wchar_t* charToWChar(char* cArray, int len) {
char wideChar[2];
wchar_t wideCharW;
wchar_t *wArray = (wchar_t *) malloc(sizeof(wchar_t) * len / 2);
int counter = 0;
int endian = BIGENDIAN;
// Check endianness
if ((uint8_t) cArray[0] == 255 && (uint8_t) cArray[1] == 254)
endian = LITTLEENDIAN;
else if ((uint8_t) cArray[1] == 255 && (uint8_t) cArray[0] == 254)
endian = BIGENDIAN;
for (int j = 2; j < len; j+=2){
switch (endian){
case LITTLEENDIAN: {wideChar[0] = cArray[j]; wideChar[1] = cArray[j + 1];} break;
default:
case BIGENDIAN: {wideChar[1] = cArray[j]; wideChar[0] = cArray[j + 1];} break;
}
wideCharW = (uint16_t)((uint8_t)wideChar[1] << 8 | (uint8_t)wideChar[0]);
wArray[counter] = wideCharW;
counter++;
}
wArray[counter] = ' ';
return wArray;
}
用法:
if (encoding[0] == 1){
// We're dealing with UCS-2 encoded Unicode with BOM
char data[frame.size];
mp3File.read(data, frame.size);
wcout << charToWChar(data, frame.size) << endl;
}