#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define BUFF_SIZE (1024*1024)
int main(int argc, char** argv)
{
if (3 != argc) {
printf("error, need input like: ./a.out xx.txt 5 \n");
return 0;
}
FILE* pFile = NULL;
FILE* writeFile = NULL;
long size;
int splitNum = atoi(argv[2]);
int perBlock;
char readBuff[BUFF_SIZE] = { 0 };
char outputFileName[BUFF_SIZE] = { 0 };
pFile = fopen(argv[1], "rb");
if (pFile == NULL) {
perror("Error opening file");
return 0;
}
else {
fseek(pFile, 0, SEEK_END); ///将文件指针移动文件结尾
size = ftell(pFile); ///求出当前文件指针距离文件开始的字节数
printf("Size of file: %ld bytes.\n", size);
if (size / atoi(argv[2]) > BUFF_SIZE) {
printf("per block limit %d bytes\n", BUFF_SIZE);
goto Fail;
}
}
perBlock = size / splitNum;
for (int i = 0; i < splitNum; ++i) {
fseek(pFile, i * perBlock, SEEK_SET);
sprintf(outputFileName, "%s_%d", argv[1], i);
writeFile = fopen(outputFileName, "ab+");
if (writeFile == NULL) {
printf("fopen %s fail\n", outputFileName);
goto Fail;
}
fread(readBuff, sizeof(char), perBlock, pFile);
fwrite(readBuff, sizeof(char), perBlock, writeFile);
fclose(writeFile);
}
Fail:
fclose(pFile);
return 0;
}