我正在从文件中读取数据并使用 Windows 套接字将其发送到服务器。以下是代码:
//Socket creation and setup code
long Begin;
long End;
char * block;
ifstream myfile;
myfile.open(filepath, ios::in | ios::binary);
Begin = myfile.tellg();
myfile.seekg(0,ios::end);
End = myfile.tellg();
unsigned long size = End - Begin;
int Div = (int)size / 1024;
int Mod = (int)size % 1024;
int len = strlen(name);
send(theSocket,(const char*)&len,sizeof(int),0);
send(theSocket,name,strlen(name),0);
send(theSocket, (const char*)&size, sizeof(unsigned long), 0);
block = new char[1024];
for (int i=0; i<Div; i++)
{
myfile.seekg(i*1024);
myfile.read(block,1024);
cout << block << endl;
send(theSocket,block,1024,0);
}
if (Mod != 0)
{
block = new char[Mod];
myfile.seekg(Div*1024);
myfile.read(block,Mod+1);
send(theSocket,block,Mod,0);
}
delete [] block;
myfile.close();
closesocket(theSocket);
WSACleanup();
我遇到的问题是,当我从文件中读取数据时block
,它最后会附加一些奇怪的字符。每次的字符都是一样的=> "ýýýý««««««««îþîþ"。无法弄清楚是什么问题。