سؤال

I'm writing a small DLL in C++ that is going to download a file from a webserver. The downloading part works fine, but when I go to write the file on the disk, it's adding extra characters on every line.

When I look at the original file (the one that was copied onto the webserver) in Notepad++, I can see that it has the CR and LF (Carriage Return and Line Feed) characters at the end of each line like it should. On the saved version, though, instead of

line of textCRLF

it looks like

line of textCR
CRLF
CR
CRLF
Another line of text...

I haven't been able to find what's causing it. Is it some kind of issue with (o)fstream?

extern "C" void TCP_get_file(char *server, char *path, char *filename){
ofstream logfile("Crashlog.txt");
WSAData wsadata;
if ((WSAStartup(MAKEWORD(2, 2), &wsadata)) != 0){
    logfile << "Error starting winsocks." << endl;
    WSACleanup();
    return;
}
int status, sock, received;
struct addrinfo hints, *servinfo;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(server, "http", &hints, &servinfo)) != 0){
    logfile << "Error getting server info:  " << gai_strerror(status) << endl;
    WSACleanup();
    freeaddrinfo(servinfo);
    return;
}
sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
connect(sock, servinfo->ai_addr, servinfo->ai_addrlen);
string request = string("GET ") + path + " HTTP/1.0\nhost: " + server + "\r\n\r\n";
if (send(sock, request.c_str(), strlen(request.c_str()), 0) == -1){
    logfile << "Error sending request to server." << endl;
    freeaddrinfo(servinfo);
    closesocket(sock);
    WSACleanup();
    return;
}
char filebuffer[5000];
string full, file;
while ((received = recv(sock, filebuffer, 4999, 0)) > 0){
    full.append(filebuffer, received);
    ZeroMemory(filebuffer, 4999);
}
full.push_back("\0");
int offset = full.find("\r\n\r\n") + 4;
file.assign(full, offset, full.size());
ofstream savefile(filename);
savefile << file;
savefile.flush();
savefile.close();
freeaddrinfo(servinfo);
closesocket(sock);
WSACleanup();
return;

}

هل كانت مفيدة؟

المحلول

the first thing to do wuld be to use binary mode on the ofstream object:

ofstream savefile(filename, std::ofstream::binary);

It will prevent ofstream from modyfying weriten data, which is done by default (in text mode).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top