Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从midi文件读取字节时出现问题_C++_File - Fatal编程技术网

C++ 从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

我想读取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 << 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}