Chaitanya
Chaitanya

Reputation: 3479

sending an image through a socket in C++

std::ifstream file(localPath.c_str(), std::ifstream::binary);

file.seekg(0, std::ifstream::beg);

while(file.tellg() != -1)
{
    char *p = new char[1024];

    bzero(p, 1024);
    file.read(p, 1024);

    printf("%ld\n", file.gcount());

    n = send(fd, p, strlen(p), 0);
    if (n < 0) {
        error("ERROR writing to socket");
    } else {
        printf("---------%d\n", n);
    }

    delete p;
}

file.close();

Actually the image which I m trying to send is png (size: 27892bytes) As far as reading is concerned every byte is being read properly. But, while writing them into socket only few bytes are being written. Need help on this.

Thanks in advance. :)

Upvotes: 0

Views: 928

Answers (1)

iabdalkader
iabdalkader

Reputation: 17332

strlen() expects a NULL terminated string, not binary image data, when you use strlen() it stops at the first NULL (or zero) byte and the image data could contain zero at the first or second byte or anywhere, so you can't use strlen() to find the size of the image buffer. you should use the buffer size instead:

n = send(fd, p, 1024, 0);

Upvotes: 6

Related Questions