#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int file_bytes(FILE *fp);//计算文本中字节个数
int main(int argc, char** argv)
{
char infile_name[50], outfile_name[50];
char *p_file_style = ".txt";
char count;
int infile_byte_count = 0, n = 0, outfile_byte_count =0;
int i = 0, filename_length = 0;
FILE *in_fp = NULL, *out_fp = NULL;
loop:
puts("请输入你要分割的txt文件名:\n");
puts("请把txt文件放到与此软件当前目录下,记住文件要加后缀,不然可能出错!\n");
scanf("%s", infile_name);
filename_length = strlen(infile_name);
in_fp = fopen(infile_name,"r");
if(in_fp == NULL)
{
puts("文件打开失败!请重试\n");
goto loop;
}
puts("正在计算文件字节个数...\n");
infile_byte_count = file_bytes(in_fp);
fclose(in_fp);
puts("计算完成...\n");
puts("请输入你要分割成几个txt文件?\n");
scanf("%d", &n);
in_fp = fopen(infile_name, "r");
if(in_fp == NULL)
{
puts("文件打开失败!终止程序...\n");
exit(0);
}
puts("分割文件中...\n");
//分割文件开始
char* p_count =NULL;
for(; i < n; ++i)
{
//修改输出文件名+统计文件
strcpy(outfile_name, infile_name);
count = (char)(i+'0');
p_count = &count;
strcat(outfile_name, p_count);
strcat(outfile_name, p_file_style);
out_fp = fopen(outfile_name,"w");
if(out_fp == NULL)
{
puts("error!\n");
exit(0);
}
char c;
while(outfile_byte_count <= infile_byte_count/n )
{
c=fgetc(in_fp);
outfile_byte_count++;
fwrite(&c, sizeof(c), 1, out_fp);
}
outfile_byte_count = 0;
fclose(out_fp);
}
fclose(in_fp);
puts("文件分割完成!\n");
return 0;
}
int file_bytes(FILE* fp)
{
char c;
int n = 0;
while((c=fgetc(fp))!=EOF)
{
n++;
}
return n;
}