Linux下C++实现远程文件传输—思路
这里举例客户端发送文件到服务端
【服务端】
//声明变量
char fileNameServer[128] = {
'\0'};
char fileChunkBuffServer[8192] = {
'\0'};
int nLen = 0;
strcpy(fileNameServer, "/home/TestUser/TestFileServer");
/*先创建一个文件,可以用touch命令*/
system("touch /home/TestUser/TestFileServer");
【客户端】
char fileNameClient[128] = {
'\0'};
char fileChunkBuffClient[8192] = {
'\0'};
strcpy(fileNameClient, "/home/TestUser/TestFileClient");//拷贝文件路径,假定这个文件已经存在
FILE *file;
if ((file = fopen(fileNameClient, "r")) == NULL) {
return;
}
do
{
fileChunkBuffClient[0] = '\0';
int nRes = fread(fileChunkBuffClient, 1, 8192, file); //读出内容到fileChunkBuffClient,已经读过的不会再读,是读取已经读过的后面的内容,8192是想要读出多少字节,nRes是实际读出多少字节
if (nRes < 0) {
fclose(file);
return;// 读取失败
} else if (nRes == 0) {
fclose(file);
break; // 读取结束
} else {
writeU32(nRes);//发送文件内容长度,多少个字节
writeBytes(fileChunkBuffClient, nRes); //发送读取的文件内容给服务端
}
} while(true);
【服务端】
fileChunkBuffServer[0] = '\0';
readU32(nLen);//接收字节长度
readBytes((char *)fileChunkBuffServer, nLen);//接收客户端发过来的文件数据
FILE *file;
if ((file = fopen(fileNameServer, "a")) == NULL) {
return;
}
fwrite(fileChunkBuffServer, 1, nLen, file); //写入语句
fclose(file); //进行文件的关闭