recv to file with winsock?

I'm just about finished with my FTP client using WinSock. I successfully connect to the server and receive file data (testing with a jpg at the moment), now I just need to store the data in a file. First of all, it's not telling me the size of the file before sending so I'm not sure what kind of buffer to put in the recv function. Second, should I be using a FILE or will an fstream object work? I'm assuming I would have to use ios::binary?
FTP protocol support SIZE command, so you could know the size of the file on the server. Anyway, you don't need it, except if you want to implement some kind of progress information, as you need to call recv() multiple times in a loop and then copy the content of the buffer supplied to recv() in a file. Yes, you can use FILE, fstream, WriteFile() or anything you want.
And yes, you need to use std::ios::binary or "wb" to write in binary mode.
Thanks. I'm a little confused by how the recv function works; here's the code I use to receive the file data:

1
2
3
4
5
6
7
8
9
fstream file;
file.open("image.jpg", ios::out|ios::binary);

char buffer[256];

while(recv(FTPsocket2, buffer, sizeof(buffer), 0))
	file << buffer;

file.close();


I've tried larger and smaller buffers as well but the image is always corrupted. The file turns out much smaller or much larger than the original depending on the size of the buffer. Would you mind posting some example code of how I'm supposed to be doing this?

EDIT: Fixed, I used a size 1 buffer and wrote only the first element. :D
Thanks for your reply.
Last edited on
Use fstream.write(), not << operator (does not work in binary mode). Using 1 byte buffer gives you nvery low download speed.
Topic archived. No new replies allowed.