开发者

Sending binary data

开发者 https://www.devze.com 2023-02-10 18:58 出处:网络
Is there any problem doing a loop of send() where \"con开发者_运维问答st void *buf\" (2nd argument) is a file descriptor of a file opened as binary mode (fopen(\"C:\\example.mp3\", \"rb\"))?Argument o

Is there any problem doing a loop of send() where "con开发者_运维问答st void *buf" (2nd argument) is a file descriptor of a file opened as binary mode (fopen("C:\example.mp3", "rb"))?


Argument of send must point to memory buffer, filled with values (bytes) you want to send. You can treat the argument const void *buf of send() as const char *buf - it is just array of chars, which will be not changed by send() function.

But, fopen() returns to you a FILE* - it is a pointer to special struct FILE. So, if you want to send the contents of the file, you should read the contents to tmp buffer using fread() function & FILE* pointer, and then fed the tmp buffer to send() function. Repeat this code with fread() & send() until you will reach a end-of-file.

Sample code (found at http://developerweb.net/viewtopic.php?pid=28854 )

int file2socket (FILE *fp, int sockfd)
{
    char tmp[8*1024];
    int len;
    int ret;

    for (ret = 0;;) {
        len = fread (tmp, 1, sizeof (tmp), fp);
        if (len == 0) {
            ret = feof (fp);
            break;
        }
        if (!send (sockfd, tmp, len, 0)) break;
    }

    return (ret);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消