54.文件按大小切割

运行结果:

完整代码:

  1 #define _CRT_SECURE_NO_WARNINGS
  2 #include <stdlib.h>
  3 #include <stdio.h>
  4 
  5 #define sorPath "111.doc"
  6 char **stoPath;
  7 
  8 //获取文件大小
  9 int getSize(char *path)
 10 {
 11     FILE *pf = fopen(path, "r");
 12 
 13     if (pf)
 14     {
 15         fseek(pf, 0, SEEK_END);
 16         int length = ftell(pf);
 17         fclose(pf);
 18         return length;
 19     }
 20 
 21     return 0;
 22 }
 23 
 24 //切割文件
 25 void devide(char *path,int n)
 26 {
 27     //分配n个地址
 28     stoPath = (char **)malloc(sizeof(char *) * n);
 29     //每个地址分配内存,并且初始化
 30     for (int i = 0; i < n; i++)
 31     {
 32         stoPath[i] = (char *)malloc(1024);
 33         sprintf(stoPath[i], "%d.doc", i);
 34         printf("%s\n", stoPath[i]);
 35     }
 36 
 37     //二进制打开源文件
 38     FILE *pfr = fopen(path, "rb");
 39     //获取大小
 40     int totalSize = getSize(path);
 41 
 42     //如果能被整除
 43     if (totalSize%n == 0)
 44     {
 45         for (int i = 0; i < n; i++)
 46         {
 47             FILE *pfw = fopen(stoPath[i], "wb");
 48             for (int j = 0; j < totalSize / n; j++)
 49             {
 50                 fputc(fgetc(pfr), pfw);
 51             }
 52             fclose(pfw);
 53         }
 54     }
 55     else
 56     {
 57         //如果不能被整除
 58         for (int i = 0; i < n - 1; i++)
 59         {
 60 
 61             FILE *pfw = fopen(stoPath[i], "wb");
 62             for (int j = 0; j < totalSize / n; j++)
 63             {
 64                 fputc(fgetc(pfr), pfw);
 65             }
 66             fclose(pfw);
 67         }
 68 
 69         FILE *pfw = fopen(stoPath[n-1], "wb");
 70         int left = totalSize - (totalSize / n) * (n - 1);
 71         for (int i = 0; i < left; i++)
 72         {
 73             fputc(fgetc(pfr), pfw);
 74         }
 75         fclose(pfw);
 76     }
 77     fclose(pfr);
 78 }
 79 
 80 //合并
 81 void merge(char *path, int n)
 82 {
 83     FILE *pfw = fopen(path, "wb");
 84 
 85     for (int i = 0; i < n; i++)
 86     {
 87         FILE *pf = fopen(stoPath[i], "rb");
 88         if (pf)
 89         {
 90             int ch;
 91             while ((ch = fgetc(pf)) != EOF)
 92             {
 93                 fputc(ch, pfw);
 94             }
 95         }
 96         fclose(pf);
 97     }
 98     fclose(pfw);
 99 }
100 
101 void main()
102 {
103     int length = getSize(sorPath);
104 
105     printf("%d\n", length);
106     devide(sorPath, 10);
107     merge("last.doc", 10);
108     system("pause");
109 }

 

转载于:https://www.cnblogs.com/xiaochi/p/8426853.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值