- /*
- * 把一个大文件文件拆分成指定的大小的几个小文件
- * Author: Daniel Chen
- * yihua.chen@hotmail.com
- */
- #include <stdlib.h>
- #include <stdio.h>
- #define MAXFILECNT 8
- static int filecount = 0;
- static char *Files[MAXFILECNT];
- static char txtBuff[1024 * 520];
- static char fname[256];
- static int flength = 512;
- int getContent(FILE *file, char *buff, int offset, int length, int *flag)
- {
- char *tmp = &buff[offset];
- int c = 0;
- int i = 0;
- *flag = 0;
- while ((c = fgetc(file)) > 0 && i < length)
- {
- tmp[i++] = (char)c;
- }
- while (c > 0 && c != '\\n')
- {
- tmp[i++] = (char)c;
- c = fgetc(file);
- }
- if (c <= 0)
- {
- fclose(file);
- *flag = 1;
- }
- tmp[i] = '\\0';
- return (i + offset);
- }
- void divide(char **files, int filecnt, const char *filename, const char *type, int divLen)
- {
- int i = 0;
- int j = 0;
- int len = 0;
- int flag = 0;
- int offset = 0;
- FILE *sf, *tf;
- if (filecnt <= 0)
- return;
- sf = NULL;
- while (1)
- {
- if (sf == NULL)
- sf = fopen(files[i], "r");
- if (sf == NULL)
- {
- printf("Error: Open file %s failed!\\n", files[i]);
- exit(1);
- }
- len = getContent(sf, txtBuff, offset, divLen - offset, &flag);
- if (flag) /* 当前文件已经读完 */
- {
- if (i >= filecnt - 1) /* 没有新的文件可读取 */
- {
- sprintf(fname, "%s_%03d.%s", filename, j++, type);
- tf = fopen(fname, "w+");
- if (tf == NULL)
- {
- printf("Create and open file %s failed!\\n", fname);
- exit(1);
- }
- fputs(txtBuff, tf);
- fflush(tf);
- fclose(tf);
- return; /* 函数退出 */
- }
- else /* 还有新的文件可读取 */
- {
- if (len >= divLen) /* 本次读取已经完成 */
- {
- sprintf(fname, "%s_%03d.%s", filename, j++, type);
- tf = fopen(fname, "w+");
- if (tf == NULL)
- {
- printf("Create and open file %s failed!\\n", fname);
- exit(1);
- }
- fputs(txtBuff, tf);
- fflush(tf);
- fclose(tf);
- i++;
- offset = 0;
- sf = NULL;
- continue; /* 继续读取下一个文件 */
- }
- else /* 本次读取尚未完成 */
- {
- i++;
- sf = NULL; /* 读取下一个文件 */
- continue;
- }
- }
- }
- else /* 当前文件还没有读取完成 */
- {
- if (len < divLen) /* 如果读取的长度不够,则出错 */
- {
- printf("Error: Read file %s error!\\n", files[i]);
- exit(1);
- }
- /* 将本次读取的内容写入新的文件 */
- sprintf(fname, "%s_%03d.%s", filename, j++, type);
- tf = fopen(fname, "w+");
- if (tf == NULL)
- {
- printf("Create and open file %s failed!\\n", fname);
- exit(1);
- }
- fputs(txtBuff, tf);
- fflush(tf);
- fclose(tf);
- /* 继续读取下一部分内容 */
- offset = 0;
- continue;
- }
- }
- return;
- }
- int main(int argc, char **argv)
- {
- int i;
- if (argc <= 4)
- {
- printf("Usage: %s target_file_name target_file_type divide_len file1 [file2 ...]\\n", argv[0]);
- system("pause");
- return EXIT_SUCCESS;
- }
- filecount = argc - 4;
- if (filecount > MAXFILECNT)
- {
- printf("Open too many files!\\n");
- return EXIT_FAILURE;
- }
- flength = atoi(argv[3]) * 1024;
- for (i = 0; i < filecount; i++)
- Files[i] = argv[4 + i];
- divide(Files, filecount, argv[1], argv[2], flength);
- return EXIT_SUCCESS;
- }
- //该片段来自于http://www.codesnippet.cn/detail/170120131744.html
来源: http://www.codesnippet.cn/detail/170120131744.html