单机模式下的文件上传与下载

tech2023-06-20  111

单机模式下的文件上传与下载,只是一个简单地示例,目前自己发现德里面存在很多问题,比如不能下载子目录中的文件,下载的文件的权限与上传的文件的权限的一致性问题。如果后期的某些项目中确实需要这个功能,再去深究。

/* 单机模式下的文件上传送和下载 * (1) 输入服务器的地址: 路径和目录名 * (2) 列出服务器中有哪些文件 * (3) 输入从服务器下载的文件名 或 上传文件到服务器的文件名 * (4) 文件下载 * (5) 文件上传送 */ #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); //list server files dp = opendir(server); if(dp == NULL) { printf("open server %s error\n", server); return -1; } fprintf(stdout, "open server %s ok\n", server); //read server dir while(1) { dir = readdir(dp); if(dir == NULL) { break; } else { printf("inode = %ld name = %s\n", dir->d_ino, dir->d_name); } } //download file printf("please input download file\n"); scanf("%s",file); //open server 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); //upload file 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; }
最新回复(0)