随手写的,可能有错误,你参考一下
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
// 输入信息
const char* filename = "gen_hapmap";
const size_t N = 10000;
int retval = 1; // 返回值
if( N == 0 )
{
printf( "parameter error.\n" );
goto error001;
}
// 打开输入文件
FILE* fin = fopen( filename, "rt" );
if( !fin )
{
printf( "Failed to open file named \"%s\".\n", filename );
goto error001;
}
// 计算需要分成几段
unsigned part = 0;
{
unsigned maxchrnum = 0;
unsigned chrnum = 0;
for( char line[N+1]; fgets(line,N+1,fin); )
{
chrnum += strlen(line);
if( strchr(line,'\n') )
{
if( chrnum-1 > maxchrnum )
maxchrnum = chrnum-1;
chrnum = 0;
}
}
if( chrnum > maxchrnum ) // 最末一行可能没有回车符
maxchrnum = chrnum;
if( ferror(fin) )
{
printf( "Failed to read file named \"%s\".\n", filename );
goto error002;
}
rewind( fin );
part = (maxchrnum+N-1)/N;
}
// 创建输出文件
FILE** fout = (FILE**)calloc( part, sizeof(FILE*) );
if( !fout )
{
printf( "Failed to call malloc function.\n" );
goto error002;
}
for( unsigned i=0; i!=part; ++i )
{
char fileout[260];
sprintf( fileout, "%s(%u-%u)", filename, i*N, i*N+N-1 );
fout[i] = fopen( fileout, "wt" );
if( !fout[i] )
{
printf( "Failed to create file named \"%s\".\n", fileout );
goto error003;
}
}
// 文件垂直分割
unsigned col = 0;
for( char line[N+1+1]; fgets(line,N+1,fin); )
{
size_t len = strlen(line);
if( line[len-1] == '\n' )
{
if( len != 1 ) // 只截得回车符
{
if( fputs(line,fout[col]) < 0 )
{
printf( "Failed to write file.\n" );
goto error003;
}
++col;
}
for( ; col!=part; ++col )
{
if( fputs("\n",fout[col]) < 0 )
{
printf( "Failed to write file.\n" );
goto error003;
}
}
col = 0;
}
else
{
if( len != N )
{
if( !feof(fin) )
{
printf( "Failed to read \"%s\"\n", filename );
goto error002;
}
if( fputs(line,fout[col]) < 0 )
{
printf( "Failed to write file.\n" );
goto error003;
}
break;
}
line[len] = '\n';
line[len+1] = '\0';
if( fputs(line,fout[col]) < 0 )
{
printf( "Failed to write file.\n" );
goto error003;
}
++col;
}
}
if( ferror(fin) )
{
printf( "Failed to read \"%s\"\n", filename );
goto error003;
}
retval = 0;
// 资源释放
error003:
for( unsigned i=0; i!=part && fout[i]; ++i )
{
fclose( fout[i] );
if( retval != 0 )
{
char fileout[260];
sprintf( fileout, "%s(%u-%u)", filename, i*N, i*N+N-1 );
remove( fileout );
}
}
free( fout );
error002:
fclose( fin );
error001:
return retval;
}