1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
int CopyFile(int src_sock)
{
auto char buf[BUFLEN];
auto FILE *file;
auto ssize_t nBytes;
auto int count = 0;
auto char fileName[strlen(buf)];
// get the filename from the client (should be a null-terminated string)
nBytes = recv(src_sock, buf, BUFLEN, 0);
if (-1 == nBytes)
{
perror("server -- recv failed");
return FALSE;
}
strcpy(fileName, buf);
// use the filename to open an output file
file = fopen(buf, "w");
// set a pointer to the data, and adjust number of bytes to write
// loop and read the rest of the data from the client in 512-byte packets,
// writing them to the local output file
while (TRUE)
{
nBytes = recv(src_sock, buf, BUFLEN, 0);
if (-1 == nBytes)
{
perror("server -- recv failed");
return FALSE;
}
count += nBytes;
if (0 == nBytes)
{
break;
}
printf("client socket = %d -- %d %s transferred\n", src_sock, nBytes, nBytes == 1 ? "byte" : "bytes");
fwrite(buf, sizeof(char), nBytes, file);
fseek(file, count, SEEK_SET);
}
// close the output file stream
fclose(file);
// write a final summary message to stdout
printf("Data saved in '%s', %d bytes written.\n", fileName, count);
return TRUE;
} // end of "CopyFile"
|