Sign in to follow this  

Appended data returns unwanted characters

This topic is 3315 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey guys, I'm appending some extra info at the end of a jpeg file, but when I read the string back, it contains some extra characters which I don't know where they are coming from. What's wrong with my code? :)
	string data = "this string will be appended to the file, and read back again";
	//[...] code that appends the data, hex editor shows the info to be correctly added

	unsigned int fsize = boost::filesystem::file_size(boost::filesystem::path(jpgfile));
	unsigned int ofs = fsize - data.size();
	cout << "Size:   " << fsize << endl;
	cout << "Offset: " << ofs << endl;

	char * indata;
	indata = new char[data.size()];

	ifstream infile (jpgfile.c_str(), ios::in || ios::binary);
	if (!infile.fail()) {
		infile.seekg(ofs);
		infile.read(indata, data.size());
		if (infile.fail()) { cout << " read failed!\n"; }
		cout << "Result: \"" << indata << "\"" << endl;
		infile.close();
	} else {
		cout << jpgfile << " could not be opened!\n";
	}



This is the output:
Size:   42485
Offset: 42424
Result: "this string will be appended to the file, and read back again²²²²½½½½½½½½¦e¦e¦e¦"



Where are those characters coming from? Cheers!

Share this post


Link to post
Share on other sites
Keep in mind that char strings are NULL terminated. You make indata EXACTLY equal to the length of the string, and neglect to stick a '\0' at the end.


char * indata;
indata = new char[data.size() + 1];//changed

ifstream infile (jpgfile.c_str(), ios::in || ios::binary);
if (!infile.fail()) {
infile.seekg(ofs);
infile.read(indata, data.size());

indata[data.size()] = '\0';//added

if (infile.fail()) { cout << " read failed!\n"; }
cout << "Result: \"" << indata << "\"" << endl;
infile.close();
} else {
cout << jpgfile << " could not be opened!\n";
}






Your code should look more like this.

Share this post


Link to post
Share on other sites

This topic is 3315 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this