For days I have been trying to read an entire PNG into a string, so I can upload it to a server via winsock2, it appears to stop reading the file after a few characters or a some sort of line break, is there any particular reason and a way of solving it.
I have tried many many solutions and this is now starting to drive me insane. The current code I am using is as follows
std::ifstream in ("some.png", ios::in|ios::binary|ios::ate );
std::string contents;
if (in)
{
in.seekg(0, in.end);
contents.resize(in.tellg());
in.seekg(0, in.beg);
in.read(&contents[0], contents.size());
in.close();
length = contents.size();
}
I have no idea what the problem could be, as I am relatively new to c++, I have trolled through google for days with no working solution.
Please help
UPDATE code posting to the server
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
return;
SOCKET fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd < 0)
throw;
SOCKADDR_IN service;
service.sin_family = AF_INET;
service.sin_port = htons(80);
LPHOSTENT host = gethostbyname("127.0.0.1");
if (!host)
throw;
service.sin_addr = *((LPIN_ADDR)*host->h_addr_list);
if (connect(fd, (SOCKADDR *)&service, sizeof(service)) < 0)
throw;
int length ;
std::ifstream in (CCFileUtils::fullPathFromRelativePath("back.png"), ios::in|ios::binary|ios::ate );
std::string contents;
if (in){
in.seekg(0, in.end);
contents.resize(in.tellg());
in.seekg(0, in.beg);
in.read(&contents[0], contents.size());
in.close();
length = contents.size();
}else
std::string str =
"POST /index.php HTTP/1.1\r\n"
"Host: metapps.co.uk\r\n"
"Accept: */*\r\n";
char buffer1 [50];
str.append( "Content-Length: 121\r\n" );
str.append( "\r\n" );
str.append( "Content-Disposition: form-data; name=\"tmp\";filename=\"photo.png\"\r\n" );
str.append( "Content-Type: image/dds\r\n" );
sprintf (buffer1, "Content-Length: %d\r\n", length);
str.append( buffer1 );
str.append( contents );
str.append( "\r\n\x01A\r\n" );
// send str ...
send(fd, str.c_str() , strlen( str.c_str() ) +1 , 0);
char ret[1024];
recv(fd,ret,strlen(ret),0);
closesocket(fd);
WSACleanup();
}
Update 2
Its something to do with the Null terminator string and the append method
If I do
str.append( "he\0llo" );
The server will only show "he"
If I do
str.append( "hello" );
I get hello, hopefully this info, can lead to a solution