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?

1
  • This might be helpful. Even if you decide to do everything yourself, it has some documentation about mp3 tags. Commented Dec 10, 2011 at 23:23

1 Answer 1

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';
Sign up to request clarification or add additional context in comments.

4 Comments

OK changed it, I forget that string has a data() to access the data, whereas vector you have to use indices.
Cool, just a few quick points, please ensure you are using #include <cstdio> 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).
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?
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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.