files are damaged after being downloaded from an ftp server through sockets

I send the command RETR and the name of the file I want to download. This file is downloaded into a buffer. After It's done I create a file with the same file extension and write this buffer into this file. The problem is that I can't open this file because, as Windows 7 says, it's damaged. I can't really think of anything it can be because of. Worth mentioning that I tried downloading bmp files, and it worked! But when it comes to downloading png, doc files, it's damaged. I can't open it :( I'm counting on your help guys because I haven't managed to find a solution myself and it seems I won't.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    char buffer[30000];
    send(serverSocket, "RETR user.png\r\n", 15, 0);

    int iResult;
    int size = 0;

    do {

        iResult = recv(dataSocket, buffer, 30000, 0);
        if (iResult > 0) {
            printf("Bytes received: %d\n", iResult);
            size = size + iResult;
        }
        else if (iResult == 0)
            printf("Connection closed\n");
        else
            printf("recv failed: %d\n", WSAGetLastError());

    } while (iResult > 0);

    cout << "the full size: " << size << endl;

    ofstream fout("test.png", ios_base::binary);
    fout.write(buffer, size);
    fout.close();
Not sure what you're doing here, but you gotta specify the binary mode if you're manually opening FTP connections and want to transfer binary files. I mean if your interfacing your program to an FTP client or something.
You were right! That was all about the binary mode. Thank you so much!
all modern software is coded to handle the minor differences in text files so it is fairly safe to always transfer in binary unless you have a specific reason not to do so. If the files are consumed by robots (eg, a simple xml parser) it can break those, or if they are fixed width, or something specific like that. Just in case you need to send text files also, and didn't want to reset the connection properties a bunch.

Topic archived. No new replies allowed.