Sign in to follow this  
ekrax

file appending

Recommended Posts

hello, i am having a problem with a simple file packer i am coding. basically all i want it to do at this point is be able to append multipe files together and save it into one file. all i have is a vector of unsigned chars, i load up a file and push back my vector with the data, open the second file do the same, etc. then i just write the vector to a file. file 1 contains this ... "hello, test 1" file 2 contains this ... "hello, test 2" (no quotes in actual file) and my output is ... "hello, test 11hello, test 22" here is the main part of the code
for (int f = 0; f < n; f++) {
		ifstream in(F_Input[f].c_str(), ios::binary);
		if (!in) {
			cout << "File does not exsist!" << endl;
			return 1;
		}
		while (!in.eof()) {
			char j;
			in.get(j);
			buffer.push_back((byte)j);
		}
		in.close();
	}
	ofstream out(F_Output.c_str(), ios::binary);
	for (int b = 0; b < buffer.size(); b ++) {
		out << buffer[b];
	}

also i should note that i just typedef unsigned char to byte. buffer is defined as vector < byte > buffer, and n is the number of files. so i am confused where the extra 1 and extra 2 comes from, i first though maybe i was accidently outputting the number of each file, but i am not. why is this happening? thanks for any help in advance.

Share this post


Link to post
Share on other sites
The problem is that when you read the last byte of a file, the EOF bit does not get set until you try to read another byte, i.e. read past the EOF. So, after you push the last byte of a file into the buffer, the EOF bit does not get set, so you try to read in another byte, which fails, so the value of j does not get modified, you add another copy of j to the buffer, and then the EOF bit is set, so you break out of the loop. The way to fix this is to do:

while(1)
{
char j;
in.get(j);
if(in.eof())
break;
buffer.push_back((byte)j);
}

Share this post


Link to post
Share on other sites

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