Problems with binary file I/O

closed account (NUCkSL3A)
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();
1
2
3
4
5
6
7
8
9
10
11
12
sendfile.seekg (0, sendfile.beg);
//
char * bin = new char[flen];
sendfile.read(bin, flen);
//memcpy(bin, "!FTPK", 5);
//flen+=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.
Thx.
Last edited on
Did you open the file as binary?
closed account (NUCkSL3A)
Yes, I did.
You haven't provided any declarations for your objects. And you don't show how they're used.
closed account (NUCkSL3A)
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:
1
2
int bytesread = sendfile.gcount();
bool testfail = sendfile.fail();

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
Topic archived. No new replies allowed.