简体   繁体   中英

C++ fwrite buffer pad string

I am editing the tag information at the end of an MP3 file. 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.

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.

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

note if you need to be certain that the buffer is null terminated then you can do this:

v.back()='\0';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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