I'm writing a program to send a file from one PC to another. I'm trying to send it using a char* buffer
, but I'm having some problems. I think it sends the buffer, but the result is a file with a size of 0 kilobytes. I suspect I'm not writing the buffer into the file, but I really don't know for certain. My buffer data is from a *bmp file. I did find another question here on almost the same thing, but I really need more explanation.
I'm using C++ Builder 2010, and it's hard find any tutorials for it. It has various components and features that may be useful.
The code:
The Client:
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);
}
The Server:
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);
}