我正在用 C++ 编写一个小 DLL,它将从网络服务器下载文件。下载部分工作正常,但是当我将文件写入磁盘时,它会在每一行添加额外的字符。
当我在 Notepad++ 中查看原始文件(复制到网络服务器上的文件)时,我可以看到它在每一行的末尾都有 CR 和 LF(回车和换行)字符,就像它应该的那样。但是,在保存的版本上,而不是
line of textCRLF
看起来像
line of textCR
CRLF
CR
CRLF
Another line of text...
我一直无法找到导致它的原因。(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;
}