我正在编写一个程序来将文件从一台 PC 发送到另一台 PC。我正在尝试使用 发送它char* buffer
,但我遇到了一些问题。我认为它发送缓冲区,但结果是一个大小为 0 KB 的文件。我怀疑我没有将缓冲区写入文件,但我真的不确定。我的缓冲区数据来自 *bmp 文件。我确实在几乎同一件事上找到了另一个问题,但我真的需要更多解释。
我正在使用 C++ Builder 2010,很难找到任何教程。它具有可能有用的各种组件和功能。
编码:
客户端:
void __fastcall TForm1::TcpServer1Accept(TObject *Sender,
TCustomIpClient *ClientSocket)
{
char *buffer;
TcpServer1->ReceiveBuf(buffer, sizeof(buffer), 0);
CreateFile(buffer); //function that creates a file from the buffer
//Drawing my bmp on the form
Slide->LoadFromFile("ScreenShotBorland.bmp");
Image1->Canvas->Draw(0, 0, Slide);
free(buffer);
}
void CreateFile(char *buffer)
{
FILE *fp = NULL;
fp = fopen("teste.bmp", "wb");
if (fp == NULL) {
MessageBox(NULL, "ERRO!", "Error", MB_OK | MB_ICONERROR);
}
fwrite(buffer, 1, sizeof(buffer), fp);
free(buffer);
fclose(fp);
}
服务器:
void __fastcall TForm1::TcpClient1Connect(TObject *Sender)
{
//Open a file to load the buffer
long lSize;
char *buffer;
size_t result;
FILE *pf2 = fopen("teste.bmp", "rb");
if (pf2 == NULL) {
MessageBox(NULL, "ERRO!", "Error", MB_OK | MB_ICONERROR);
}
fseek(pf2, 0, SEEK_END);
lSize = ftell(pf2);
rewind(pf2);
//allocate the buffer in memorie
buffer = (char*) malloc(sizeof(char) * lSize);
if (buffer == NULL)
MessageBox(NULL, "ERRO!", "Error", MB_OK | MB_ICONERROR);
result = fread(buffer, 1, lSize, pf2);
if (result != lSize)
MessageBox(NULL, "ERRO!!!", "Error", MB_OK | MB_ICONERROR);
//Transferring the file
if (TcpClient1->Active)
TcpClient1->SendBuf(buffer, sizeof(buffer), 0);
free(buffer);
fclose(pf2);
}