我在做一个用网络传输视频文件的时候发现 怎么读出来的长度和指定的长度不同呀?我的代码如下:/  望高手指点,谢谢!//视频文件发送线程
UINT FileSendThread(LPVOID pParam)
{
int reh;
LPDWORD cbRet = 0;
CFile  hFile; 
DWORD dwFlags;
DWORD SendLen;
DWORD dwReadLength;
DWORD dwBytesRead;
int status;
LPWSABUF SendBuf;
//分配发送缓冲区
SendBuf=(LPWSABUF)GlobalAllocPtr(GHND,sizeof(WSABUF));
SendBuf->buf = (char *)malloc(BUFSIZE);


status=hFile.Open(theApp.SendFilePath,CFile::modeRead);
dwFlags = MMIO_CREATE | MMIO_WRITE;
if(status==0)
{
    //释放发送缓冲区
    free(SendBuf->buf);
    return -1;
}
else
{
    while(1)
    {
//每次读数据32k,(dwReadLength已经定义为32767,)
dwBytesRead = hFile.Read(SendBuf->buf, dwReadLength);
int aaa = strlen(SendBuf->buf);
 (为什么dwBytesRead 为32767,而aaa 求出来的长度和它完全不同呢???我这样通过sendto()发送过去会不会有问题??)
if(dwBytesRead==0)
{
             //发送完成

    //关闭文件
    hFile.Close();
    //释放发送缓冲区
    free(SendBuf->buf);
    AfxMessageBox("发送完成");
    break;
         }
SendBuf->len = dwBytesRead;

reh = sendto(theApp.sockM,
         (char*)SendBuf->buf,
strlen(SendBuf->buf),
0,
(struct sockaddr*)&(theApp.remote),
sizeof(theApp.remote));

if(reh == SOCKET_ERROR)
{
AfxMessageBox("");
closesocket(theApp.sockM);
WSACleanup();
return -1;
}
Sleep(250);
    }        
}
//文件发送标志置为FALSE
theApp.m_FileSend=FALSE; 
return 0;
}
 为什么dwBytesRead 为32767,而aaa 求出来的长度和它完全不同呢???我这样通过sendto()发送过去会不会有问题??

解决方案 »

  1.   

    //每次读数据32k,(dwReadLength已经定义为32767,)
    dwBytesRead = hFile.Read(SendBuf->buf, dwReadLength);
    int aaa = strlen(SendBuf->buf);问题在于strlen()是求字符串长度的,从头开始扫描字符串,到'\0'为止,所以aaa和dwBytesRead的值是不一样的。还有后面sendto的时候,就不应该用strlen表示要发送的字节数了。
      

  2.   

    楼上正解。
    处理一下就可以了。
    malloc(n+1);
    buf[n+1]='\0';
      

  3.   

    strlen是用来处理字符串的,你的内容应该不是字符串信息,而是二进制的。