Problems with binary file I/O

Hello, I am trying to make a program that sends a file from one computer to another, as a project for myself. The below code works fine for text files, but for some reason, doesn't read the entire file if it is a binary.

sendfile.seekg (0, sendfile.end);
int flen = sendfile.tellg();
sendfile.seekg (0, sendfile.beg);
char * bin = new char[flen];, flen);
//memcpy(bin, "!FTPK", 5);
int linelength = 0;
fileline = bin;
if(fileline.length() > flen)
fileline.erase(flen, -1);

I do not know what I am doing wrong. Perhaps it is some oversight, but it looks like it should work. I am ready to answer any questions you might have.
Last edited on
Did you open the file as binary?
Yes, I did.
You haven't provided any declarations for your objects. And you don't show how they're used.
Here it is:
ifstream sendfile(filepath.c_str(), ios::binary);
flen is an integer that finds the length of the file. It works fine. The erase part of the code is used as a fix for another bug, but is not important here.
I used this:
int bytesread = sendfile.gcount();
bool testfail =;

and it showed nothing wrong. Bytesread showed the correct number of bytes, and it did not fail.
Last edited on
One problem might be that in binary mode \r\n are two bytes, but in text mode they get converted to \n.
Ok, so bin is filled with flen bytes, and is a full copy of the file. So there's nothing wrong with that stuff. What about the sending/receiving code?
I would guess that fileline is a string and you are treating it as a nul-terminated string somewhere rather than as a sequence of bytes.
That's right.
fileline = bin;

should be
fileline.assign(bin, flen);

It didn't occur to me fileline would be used to send the data.
Last edited on
Registered users can post here. Sign in or register to post.