i'm trying to develop a little web server in C++ but i have a problem when i try to read an image file and write it in a socket buffer. I found a similar function written in C that works perfectly, i cannot understand why my method doesn't work, when i connect to the server by browser and open an image file i got this output.
"The image "http://127.0.0.1:7777/myimage.jpg" cannot be displayed because it contains errors."
This is my method:
std::string
Client::getFileContent(const std::string& name)
{
std::ifstream f; f.open(name.c_str(), std::ios::binary);
if( !f.is_open() ) {
return (std::string(""));
} else {
f.seekg(0, std::ios::end);
unsigned int length = f.tellg();
f.seekg(0, std::ios::beg);
char* buffer = new char[length];
f.read(buffer, length);
f.close();
return ( std::string(buffer) );
}
}
And then i write it in a socket buffer(use nspr socket):
void
Socket::send(const std::string& s)
{
if(PR_Send(sock, s.c_str(), s.length(), 0, PR_INTERVAL_NO_WAIT) == -1) {
throw ( Exception::Exception(Exception::Exception::SOCKET_SEND) );
}
}
And this is the function i found on web, i cannot understand why this works perfectly and mine doesn't work O.o:
while ( (ret = read(file_fd, buffer, BUFSIZE)) > 0 ) {
(void)write(fd,buffer,ret);
Thank you very much :)
You problem is here:
Creating a string from a
char *
will stop at the first 0 byte, while an image may contain a lot. instead of returning a string, return avector<char>
like