一、概述
文件传输,分为文件名字和文件内容。
传递文件名后,等待另外一端创建相应的文件并回复,然后在开始传输文件内容。
以下程序还设计到目录的查询。
二、目录的查询
主要头文件
#include <dirent.h>
主要函数
//获取当前目录的名字,并以字符串的形式保存在DirBuf里面
getcwd(DirBuf , sizeof(DirBuf))
//打开当前目录,并且用dir指针指向当前目录的信息
DIR *dir;
dir = opendir(DirBuf);
//依次获取当前目录的文件信息,并且用一个结构体指针指向返回的数据
struct dirent *dirinfo;
dirinfo = readdir(dir)//当读取完整个文件夹之后,会返回NULL
三、文件传输
因为文件传输很类似,所以这里就只演示客户端从服务器下载文件的程序代码
客户端会先发送要下载的文件的文件名字给服务器,服务器会根据名字打开文件。打开成功之后会给客户端发送确认信息。这时候就开始文件的传输
3.1客户端代码
在服务器端一行一行的传输给客户端,在客户端用fputs来写入文件
/**
* @brief 下载文件
*
* @param acceptfd
* @param msg
* @return int
*/
int do_downLoad(int acceptfd , MSG *msg)
{
/*
1、在本地创建文件
2、发送要下载的文件名给服务器
3、接收内容
*/
FILE *fp = NULL;
printf("in downLoad.\n");
msg->type = D;
fp = fopen(msg->filename,"w");
if(fp == NULL)
{
printf("fail to create file.\n");
return -1;
}
/*发送文件名字*/
if(send(acceptfd , msg, sizeof(MSG) , 0) < 0)
{
perror("send");
exit(0);
}
/*等待服务器确认有此文件*/
if(recv(acceptfd , msg , sizeof(MSG) , 0) < 0)
{
perror("recv");
exit(0);
}
if(strncmp(msg->filename , EXIST , strlen(EXIST) - 1) != 0)
{
printf("file not exist.\n");
fclose(fp);
return -1;
}
/*写入内容*/
while(recv(acceptfd , msg , sizeof(MSG) , 0) > 0)
{
if(msg->filecontent[0] == '\0')
{
break;
}
printf("%s" , msg->filecontent);
fputs(msg->filecontent , fp);
}
/*关闭文件*/
fclose(fp);
return 0;
}
3.2服务器端代码
用fopen函数打开文件,然后使用fgets一行一行的读取文件内容,如果读到了文件末尾,fgets会返回一个NULL
/**
* @brief 发送文件到客户端
*
* @param acceptfd
* @param msg
* @return int
*/
int do_download(int acceptfd ,MSG *msg)
{
/*
1、打开客户端要下载的文件
2、如果打开文件失败了就返回“fail”
3、如果成功就就开始传输
4、发送完毕之后就要发送一个空字符
*/
FILE *fp = NULL;
printf("in download.\n");
if((fp = fopen(msg->filename , "r")) == NULL)//用读模式打开文件
{
/*打开文件失败*/
printf("open file fail.\n");
strcpy(msg->filecontent , "fail");
send(acceptfd , msg , sizeof(MSG) , 0);
return -1;
}
strcpy(msg->filename, EXIST);
if(send(acceptfd , msg , sizeof(MSG) , 0) < 0)
{
perror("send");
return -1;
}
/*fgets 读到了文件末尾,会返回NULL*/
while(fgets(msg->filecontent , 512 , fp) != NULL)
{
printf("%s" , msg->filecontent);
send(acceptfd , msg , sizeof(MSG) , 0);
}
/*发送一个空字符代表结束*/
msg->filecontent[0] = '\0';
if(send(acceptfd , msg , sizeof(MSG) , 0) < 0)
{
perror("send");
return -1;
}
return 0;
}