C++ 从midi文件读取字节时出现问题
我想读取midi文件的单个字节,我编写了一个简单的程序来尝试这样做:C++ 从midi文件读取字节时出现问题,c++,file,C++,File,我想读取midi文件的单个字节,我编写了一个简单的程序来尝试这样做: ifstream file{"D:\Descargas\OutFile.midi" }; if (!file.is_open()) cout << "Not open" << endl; // It passes this test char c; for (unsigned i = 0; i < 100; ++i) { file >> c; cout &l
ifstream file{"D:\Descargas\OutFile.midi" };
if (!file.is_open())
cout << "Not open" << endl; // It passes this test
char c;
for (unsigned i = 0; i < 100; ++i) {
file >> c;
cout << c << endl; // Output is -52, but it must output 4D which is 77 in decimal
}
ifstream文件{“D:\Descargas\OutFile.midi”};
如果(!file.is_open())
coutc;
cout您需要将输出配置为以十六进制打印,并用0
将每个数字填充到2
的宽度。您还需要将字符c
强制转换为int
,这样它就不会以字母形式输出:
// configure output
cout << std::hex << std::setfill('0') << std::uppercase;
char c;
// read in the while block so you only use it if the read succeeds
while(file >> c)
{
// set the width and convert to an integer
cout << std::setw(2) << int(c) << endl;
}
//配置输出
实际上,\
字符必须转义。您应该以二进制方式打开文件,否则当文件碰巧包含0x0d/0x0a序列或0x1a字节时,很可能会得到不好的结果。@MichaelBurr为什么这些序列会违反规则?我注意到,如果我将file.read(&c,1)
放在file.read(&c,1)
中,而不是放在file>>c
中,那么它会按预期工作,但我不知道为什么。鲜为人知的提示-在API级别,Windows会接受“/”作为路径分隔符(通常不会在命令行中)。这个替代反斜杠的方法应该也可以,而且我发现它更容易阅读:ifstream文件{“D:/Descargas/OutFile.midi}代码>