0

I'm fairly new with C++ and am trying to read and write binary file. I have used the read and write functions to read text from one file and output it to a new file. However the following characters always appear at the end of the created text file "ÌÌ". Is a particular character indicating the end of file being saved in the character buffer?

int main(){
ifstream myfile("example.txt", ios::ate);
ofstream outfile("new.txt"); 
ifstream::pos_type size; 
char buf [1024]; 

if(myfile.is_open()){       
    size=myfile.tellg(); 
    cout<<"The file's size is "<<(int) size<<endl;
    myfile.seekg(0,ios::beg);
    while(!myfile.eof()){
        myfile.read(buf, sizeof(buf)); 
    }
    outfile.write(buf,size); 
    }
else 
    cout<<"Error"<<endl;

myfile.close();
outfile.close();
cin.get();
return 0;

}
2
  • 1
    If you use eof(), you don't understand how to use iostreams. Please read the reference documentation until you understand what each part of your code does. It's all documented, but you have to read it and cannot just guess what might happen.
    – Kerrek SB
    Sep 27, 2013 at 22:20
  • Should also note that using close() is completely unnecessary in C++ because of RAII. Sep 27, 2013 at 22:34

1 Answer 1

2

Not the only problem with your code (try it on a file bigger than 1024 bytes) but since you are doing binary I/O you need

ifstream myfile("example.txt", ios::ate|ios::binary);
ofstream outfile("new.txt", ios::binary);
2
  • Right - because a text file will lose characters as it's read, the final count won't be the same as the tellg indicated. Sep 27, 2013 at 22:20
  • The buffer will only hold 1kb, but I was thinking of splitting larger files in order to eventually send it in a socket. (Specifying ios::binary did remove the strange characters at the end)
    – Sebastien
    Sep 27, 2013 at 22:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.