Sebastien
Sebastien

Reputation: 39

C++ writing to text using buffer returns non ascii character at end of file.

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;

}

Upvotes: 0

Views: 623

Answers (1)

john
john

Reputation: 87957

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);

Upvotes: 2

Related Questions