• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Appending Files in C++

phantom404

Golden Member
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:😱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.
 
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
 
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.
 
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.
 
Back
Top