我是否错误地集中了这些字符数组?
Am I concentrating these character arrays incorrectly?
我一直在尝试用 C++ 从头开始创建一个 MIDI 文件。我将不同的块(和部分块)分成不同的字符数组。
我的代码:
#include <iostream>
#include <fstream>
#include <cstring>
int main(int, char* []) {
std::ofstream MIDIfile ("example.mid")
char header[] = { /* hex data */ };
char track_header[] = { /* hex data */ };
char track_data[] = { /* hex data */ };
MIDIfile << strcat(header, strcat(track_header, track_data));
MIDIfile.close();
return 0;
}
我唯一的问题是写入文件时,只写入了 81 个字节中的 8 个。是否有一个原因?我做错了什么吗?
此致,暗影追猎者75
您必须了解 strcat()
的作用。这条线永远行不通。实际上,更好的是,永远不要使用 strcat()
。太垃圾了。
MIDIfile << strcat(header, strcat(track_header, track_data));
您有十六进制数据的二进制缓冲区,只需使用 write()
函数:
MIDIfile.write(header, sizeof(header));
...
一次写入一个缓冲区。
formatted operator<<
function for char
arrays or pointers 用于打印 空终止 字符串。如果您的 "hex data" 包含任何零(二进制零,0
,而不是字符 '0'
),那么它将作为终止符。
更不用说您的缓冲区溢出了,因为您追加到一个固定大小的数组中,该数组的大小专门针对您初始化它所用的数据。
解决方案首先是不要使用任意二进制数据作为字符串(strcat
函数也期望数据是空终止字符串)但是作为原始数据。其次你需要使用the write
function来写入任意数据。
我一直在尝试用 C++ 从头开始创建一个 MIDI 文件。我将不同的块(和部分块)分成不同的字符数组。
我的代码:
#include <iostream>
#include <fstream>
#include <cstring>
int main(int, char* []) {
std::ofstream MIDIfile ("example.mid")
char header[] = { /* hex data */ };
char track_header[] = { /* hex data */ };
char track_data[] = { /* hex data */ };
MIDIfile << strcat(header, strcat(track_header, track_data));
MIDIfile.close();
return 0;
}
我唯一的问题是写入文件时,只写入了 81 个字节中的 8 个。是否有一个原因?我做错了什么吗?
此致,暗影追猎者75
您必须了解 strcat()
的作用。这条线永远行不通。实际上,更好的是,永远不要使用 strcat()
。太垃圾了。
MIDIfile << strcat(header, strcat(track_header, track_data));
您有十六进制数据的二进制缓冲区,只需使用 write()
函数:
MIDIfile.write(header, sizeof(header));
...
一次写入一个缓冲区。
formatted operator<<
function for char
arrays or pointers 用于打印 空终止 字符串。如果您的 "hex data" 包含任何零(二进制零,0
,而不是字符 '0'
),那么它将作为终止符。
更不用说您的缓冲区溢出了,因为您追加到一个固定大小的数组中,该数组的大小专门针对您初始化它所用的数据。
解决方案首先是不要使用任意二进制数据作为字符串(strcat
函数也期望数据是空终止字符串)但是作为原始数据。其次你需要使用the write
function来写入任意数据。