为什么在将char数组复制到结构体时memcpy不工作? [英] Why doesn't memcpy work when copying a char array into a struct?
本文介绍了为什么在将char数组复制到结构体时memcpy不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#define buffer 128
int main(){
char buf[buffer]="";
ifstream infile("/home/kevin/Music/test.mp3",ios::binary);
infile.seekg(-buffer,ios::end);
if(!infile || !infile.read(buf,buffer)){
cout<<"fail!"<<endl;
}
ID3v1 id3;
cout<<sizeof(id3)<<endl;
memcpy(&id3,buf,128);
cout<<id3.header<<endl;
}
struct ID3v1{
char header[3];
char title[30];
char artist[30];
char album[30];
char year[4];
char comment[28];
bool zerobyte;
bool track;
bool genre;
};
当我做memcpy时,似乎将太多的数据推入头字段。我需要遍历每个structs成员并复制数据吗?我也使用c ++,但这似乎更多的是一个C的战略。对于c ++有更好的方法吗?
When I do the memcpy, it seems to be pushing too much data into the header field. Do I need to go through each of the structs members and copy the data in? I'm also using c++, but this seems more of a "C" strategy. Is there a better way for c++?
推荐答案
如所有的注释,或当打印C字符串时,操作符<< <期望字符序列被'\0'终止)。
As noted in all the comments (you are missing the '\0' character, or when printing C-Strings the operator<< is expecting the sequence of characters to be '\0' terminated).
尝试:
std::cout << std::string(id3.header, id3.header+3) << std::endl;
这将打印标题字段中的三个字符。
This will print the three characters in the header field.
这篇关于为什么在将char数组复制到结构体时memcpy不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文