实现如下功能:
1.读取参数
-s source.dat:指定待分割的文件名称;
-d dest:指定分割后的文件模板名称,其文件将以dest0001.dat,dest0002.dat.....的方式进行命名
-n size:指定分割后的文件大小
2.用法
./split_file -s source.dat -d dest -n 10485760
以10M为单位进行文件分割
3.缺省参数
默认的源文件为source.dat
默认的分割文件模板名称为dest
默认的文件分割大小为1M(1048576Bytes)
./split_file -n 10485760
与.2中的命令执行的结果一直
以下为C++源码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_PATH 260
/**
* -s:source file
* -d:destination file template
* -n:size of destination file
*/
int main(int argc,char**argv)
{
int opt = 0;
char* optstr = NULL;
char* program_name = argv[0];
char* p = strchr(program_name,'.');
if(p == NULL)
{
}
else
{
*p = 0;
}
char source_file[MAX_PATH] = {0};
char dest_file[MAX_PATH] = {0};
unsigned long file_size = 1024*1024;//1M
unsigned long FILE_SIZE = file_size;
//the default source file name is the same as program name but ext
//the destination file name is the same as program name but ext.
snprintf(source_file,MAX_PATH,"%s.src",program_name);
snprintf(dest_file,MAX_PATH,"%s.dst",program_name);
while((opt = getopt(argc,argv,"s:d:n:")) != -1)
{
switch(opt)
{
case 's':
snprintf(source_file,MAX_PATH,"%s",optarg);
break;
case 'd':
snprintf(dest_file,MAX_PATH,"%s.part",optarg);
break;
case 'n':
file_size = atol(optarg);
FILE_SIZE = file_size;
break;
default:
printf("invalid options!\n");
}
}
FILE* src_file = fopen(source_file,"rb");
if(src_file == NULL)
{
printf("open %s file error!\n",source_file);
return -1;
}
char* data_block = new char[file_size];
FILE* dst_file = NULL;
char split_file[MAX_PATH];
unsigned int count = 0;
//write the same size file
while((file_size = fread(data_block,1,FILE_SIZE,src_file)) == FILE_SIZE)
{
snprintf(split_file,MAX_PATH,"%s%04d",dest_file,count++);
dst_file = fopen(split_file,"wb");
if(dst_file == NULL)
{
printf("open %s error!\n");
return -1;
}
fwrite(data_block,1,file_size,dst_file);
fclose(dst_file);
}
//write the last block data
snprintf(split_file,MAX_PATH,"%s%04d",dest_file,count);
dst_file = fopen(split_file,"wb");
if(dst_file == NULL)
{
printf("open %s error!\n");
return -1;
}
fwrite(data_block,1,file_size,dst_file);
fclose(dst_file);
delete[] data_block;
//close the source file
fclose(src_file);
return 0;
}