0

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?

Phil M
  • 3
  • 1
  • [This](http://id3lib.sourceforge.net/) might be helpful. Even if you decide to do everything yourself, it has some documentation about mp3 tags. – Piotr Praszmo Dec 10 '11 at 23:23

1 Answers1

3

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';
111111
  • 15,686
  • 6
  • 47
  • 62
  • OK changed it, I forget that string has a data() to access the data, whereas vector you have to use indices. – 111111 Dec 10 '11 at 23:17
  • Cool, just a few quick points, please ensure you are using #include rather than stdio.h this will require you to prefix fwrite as std::fwrite and so on. (I would also recommend checking out fstreams, that is the more C++ way of doing file IO). – 111111 Dec 10 '11 at 23:20
  • What if the title (the user enters on command line) has a space in it? It only seems to take the first part and not the second? – Phil M Dec 10 '11 at 23:23
  • I am sorry are you referring to using streams to get track names? if you use the stream operator (>>) with cin on a string it will indeed split the string into tokes delimited by a space. However you can use std::getline to fetch an entire line (until the user presses enter) regardless of space. std::getline(std::cin, my_string); – 111111 Dec 10 '11 at 23:26