大文件切割工具

大文件切割工具
往往超大型的日志文件,打开会非常慢或者无法打开,导致无法查看日志信息,不方便调试的开展。
下面介绍自己编写的大文件切割程序,程序比较简单,使用Qt,C和C++,能够处理2.1G以上的大文件,适合初学者阅读。下面贴代码:
#include <stdio.h>
#include <QString>
#include <QFileInfo>
#include <string>
#include <windows.h>

using namespace std;

int main(int argc, char *argv[])
{
char bigFilePath[1024];
int detachedFileCount = 2;
printf("请按照格式输入参数(大文件路径 分割后文件数量),注:不支持中文路径\n");
scanf("%s", bigFilePath);
scanf("%d", &detachedFileCount);


string bigFileAbsolutePath = string(bigFilePath);//大文件的绝对路径
//处理文件后缀
unsigned sybmolIndex = bigFileAbsolutePath.find_last_of(".");//后缀下标
string prefixPath = bigFileAbsolutePath.substr(0, sybmolIndex);//前缀
string subfixPath = bigFileAbsolutePath.substr(sybmolIndex);//后缀


//打开文件
FILE *file = fopen(bigFileAbsolutePath.c_str(), "r");
if (file == NULL)
{
printf("文件打开失败!!");
return 0;
}


QFileInfo fileInfo(QString::fromStdString(bigFileAbsolutePath));
long long originalFileSize = fileInfo.size();


long long detachedFileSizeMax = originalFileSize / detachedFileCount;


//开始将大文件分解为小文件
for (int i = 1; i <= detachedFileCount; ++i)
{
char c[2];
itoa(i, c, 10);
string newFilePath = prefixPath + c + subfixPath;
FILE *newFile = fopen(newFilePath.c_str(), "w");
if (newFile == NULL)
{
printf("文件打开%s失败", newFilePath.c_str());
return 0;
}


long long currentFileSize = 0;


while (currentFileSize <= detachedFileSizeMax && !feof(file))
{
char line[1024];
fgets(line, 1024, file);
fputs(line, newFile);
currentFileSize += string(line).length();
}


fflush(newFile);
fclose(newFile);
printf("生成%s成功!\n", newFilePath.c_str());
}
printf("文件已全部写入");


Sleep(1000);
 
return 0;
}
建立Qt工程,直接将代码复制到main.cpp中即可运行。项目工程,exe执行文件无法发布,有需要的私信。

猜你喜欢

转载自blog.csdn.net/zxgmlcj/article/details/78493269