c++ - 为什么将 char 数组复制到结构中时 memcpy 不起作用?

标签 c++ file-io struct memcpy id3

#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 时,它似乎将太多数据推送到 header 字段中。我是否需要遍历每个结构成员并将数据复制进去?我也在使用 C++,但这似乎更像是一种“C”策略。有没有更好的 c++ 方法?

最佳答案

如所有评论中所述(您缺少 '\0' 字符,或者在打印 C 字符串时,运算符 << 期望字符序列以 '\0' 终止)。

尝试:

std::cout << std::string(id3.header, id3.header+3) << std::endl;

这将打印标题字段中的三个字符。

关于c++ - 为什么将 char 数组复制到结构中时 memcpy 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9649919/

相关文章:

python - 处理 python 中的错误

c - 释放结构内的内存时程序崩溃

C++ 创建两个具有重叠内存的变量

c++ - 如何通过编译时 "if"返回 T 值?

c++ - OpenCV3 - 访问标签质心

c++ - 实时应用的OpenCV fastNlMeansDenoising的替代方法?

c# - 命令行应用程序从 C# 中的文件读取

c++ - 模数中的线性组合 C++

java - 高效地将大量数据加载到 Jtable

无法将数组分配给结构属性