简体   繁体   English

C ++ fwrite缓冲垫字符串

[英]C++ fwrite buffer pad string

I am editing the tag information at the end of an MP3 file. 我正在编辑MP3文件末尾的标签信息。 When I use fwrite to change, for example, the title and artist, if the title/artist is not the same length as before, it overlaps with existing data. 例如,当我使用fwrite更改标题和艺术家时,如果标题/艺术家的长度与以前不同,则它将与现有数据重叠。

Ex: Title: Example Song 例如:标题:歌曲范例

fwrite("Example Song 2", 30, 1, filename);

...new title does not use all thirty bytes. ...新标题不会使用全部三十个字节。

Is there a way to pad the string before writing to get it to be thirty bytes? 有没有一种方法可以在写入之前填充字符串以使其成为三十个字节? Or how can I erase the existing thirty bytes allocated for title and write my new title back to the file? 或者如何擦除分配给标题的现有三十个字节,然后将新标题写回到文件中?

If I have got your question right you want to know how to pad a string to 30 bytes so that it mask the whole field. 如果我有正确的问题,您想知道如何将字符串填充为30个字节,以使其覆盖整个字段。

One way of doing this might be: 一种方法是:

#include <vector>
#include <string>

...

std::string s("Example Song 2");  //string of title
std::vector<char> v(s.begin(), s.end());  //output initialized to string s

v.resize(30,'\0');  //pad to 30 with '\0'

fwrite(&v[0],30,1,file);

Note this method has a major plus that if the title is greater than 30 chars then the resize will truncate it reducing the chance of overflows 请注意,此方法的主要优点是,如果标题大于30个字符,则调整大小将截断它,从而减少了溢出的机会

note if you need to be certain that the buffer is null terminated then you can do this: 请注意,如果您需要确定缓冲区为null终止,则可以执行以下操作:

v.back()='\0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM