单机模式下的文件上传与下载,只是一个简单地示例,目前自己发现德里面存在很多问题,比如不能下载子目录中的文件,下载的文件的权限与上传的文件的权限的一致性问题。如果后期的某些项目中确实需要这个功能,再去深究。
#include <stdio.h>
#include <sys/types.h>
#include <grp.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#define MAX_BUFF_SIZE (1024)
int main(int argc
, const char *argv
[])
{
DIR
*dp
= NULL;
int fd
= 0;
struct dirent
*dir
= NULL;
char server
[MAX_BUFF_SIZE
] = { 0 };
char server_dir
[MAX_BUFF_SIZE
] = { 0 };
int src_fd
= -1;
int dst_fd
= -1;
char file
[MAX_BUFF_SIZE
] = { 0 };
char upload_file
[MAX_BUFF_SIZE
] = { 0 };
char buf
[MAX_BUFF_SIZE
] = { 0 };
int ret
= -1;
fprintf(stdout, "please input server path!\n");
scanf("%s", server
);
strcpy(server_dir
, server
);
dp
= opendir(server
);
if(dp
== NULL)
{
printf("open server %s error\n", server
);
return -1;
}
fprintf(stdout, "open server %s ok\n", server
);
while(1)
{
dir
= readdir(dp
);
if(dir
== NULL)
{
break;
}
else
{
printf("inode = %ld name = %s\n", dir
->d_ino
, dir
->d_name
);
}
}
printf("please input download file\n");
scanf("%s",file
);
src_fd
= open(strcat(strcat(server
,"/"),file
), O_RDONLY
);
if(src_fd
< 0)
{
fprintf(stderr, "open download file :%s\n", file
);
return -1;
}
printf("open download file %s success\n", file
);
dst_fd
= open(file
, O_CREAT
| O_WRONLY
, 0777);
if(dst_fd
< 0)
{
printf("create file %s error\n", file
);
return -2;
}
printf("create file %s success\n",file
);
while((ret
= read(src_fd
, buf
, MAX_BUFF_SIZE
)) > 0)
{
if(ret
< MAX_BUFF_SIZE
)
{
break;
}
write(dst_fd
, buf
, ret
);
}
write(dst_fd
, buf
, ret
);
printf("please input upload file\n");
scanf("%s", upload_file
);
src_fd
= open(upload_file
, O_RDONLY
);
if(src_fd
< 0)
{
printf("open file %s error\n", upload_file
);
return -1;
}
sprintf(server_dir
, "%s/%s", server_dir
, upload_file
);
dst_fd
= open(server_dir
, O_CREAT
| O_WRONLY
, 0777);
if(dst_fd
< 0)
{
printf("create file %s error\n", upload_file
);
return -2;
}
while((ret
= read(src_fd
, buf
, MAX_BUFF_SIZE
)) > 0)
{
if(ret
< MAX_BUFF_SIZE
)
{
break;
}
write(dst_fd
, buf
, ret
);
}
write(dst_fd
, buf
, ret
);
close(dst_fd
);
close(src_fd
);
closedir(dp
);
return 0;
}
转载请注明原文地址:https://tech.qufami.com/read-11075.html