Appending Files in C++

phantom404

Golden Member
Nov 2, 2004
1,460
2
81
I written a small program, something to get me back into c++ and just wanted to fool around, to take one file and append it to another file. What I've done is taken to files that are the same(data and size) and just appended one to the other. When I did this however I get one extra byte on the file being appended to.

here is how im opening the files
myfile1.open(file1.c_str(), ios::in | ios::ate | ios::binary);
myfile2.open(file2.c_str(), ios::eek:ut | ios::binary);

here is where im appending the files
if (myfile2.is_open())
{
while (!myfile2.eof())
{
myfile2.get(ch);
myfile1.put(ch);

}
myfile1.close();
myfile2.close();
}

No clue where the extra byte is coming from.

thanks in advance.
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
Guess only.

You are testing for the end of file after a get()/put()

The get() may not be returning anything, but you are still outputing something
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
Guess only.

You are testing for the end of file after a get()/put()

The get() may not be returning anything, but you are still outputing something

Most likely the problem. You could either check for a null value on ch after the get, or do a get before the while loop starts, a put first thing in the while loop, and then get again at the end of the loop. That way if the file is empty as well it won't put anything in the other file.

If you think about it, there should always be one more get then put whereas your loop has just as many puts as gets.
 

Cogman

Lifer
Sep 19, 2000
10,284
138
106
Originally posted by: Common Courtesy
Guess only.

You are testing for the end of file after a get()/put()

The get() may not be returning anything, but you are still outputing something

Bingo! I believe the answer is something like putting while(myfile2.get(c) && !myfile2.eof()) in the loop (a bit mess though) or putting the reading into a function and returning the eof as the value of said function and looping based on the function.

Another solution is to check eof before put.

And yet another is calling a get before the loop, then calling put then get.

And one more solution would be to use peek after put.