There is no clear concept in your code and you are mixing C and C++ library functions for similar tasks (e.g. using C++ and C streams for file operations).
I don't see actually where and why your code fails, but here are some tips:
Your code does not check for errors. You should check the return value of each function that might return an error state and handle exceptions (e.g. when opening the a file with
ifstream
fails). Upon errors break execution and display an error message.
Getting a pointer to the file name for a given full path is quite simple (your code is much too complicated and there is no need for an additional buffer with const strings):
const char * filename = strrchr(fpath, '\\');
if (filename)
filename++;
else
filename = fpath;
Then you are sending two strings but without the trailing NULL. How does the receiver should know how many bytes he has to read?
The common solution for this problem is sending the sizes first (as binary values and not as strings) followed by the content. Such an implementation is called a transfer protocol and should be defined before writing any code line. It is usally implemented by defining a structure. In your case it might look like:
#include <stdint.h>
struct myprotocol {
uint32_t namelen;
uint32_t filesize;
char filename[1];
};
It can be used like
uint8_t buf[sizeof(myprotocol) + MAX_FILE_NAME_LEN];
prot * myprotocol = static_cast<myprotocol*>(buf);
prot->namelen = strlen(filename);
prot->filesize = filesize;
strcpy(prot->filename, filename);
if (send(socket, buf, sizeof(myprotocol) + prot->namelen, 0) < 0)
{
return; }
The receiver can use a similar buffer and read
sizeof(myprotocol)
into that buffer. Then he can read
namelen
bytes at the corresponding buffer location followed by reading the image data:
recv(socket, buf, sizeof(myprotocol), 0);
recv(socket, &prot->filename[1], prot->namelen, 0);
The advantage of this method is that the receiver exactly knows how many bytes has been send and can provide or allocate buffers accordingly.
If your program still not works as expected then (showing no now provided error messages), you should run it within a debugger.