c文件合并

C 文件合并

问题描述

同类型文件进行合并,如下图对文件夹中的文件按文件名称顺序依次合并;
在这里插入图片描述

解决方法

  1. 后缀匹配
void ForeachFile(const string path, const string &type, vector<string> &files)
{
    _finddata_t data;
    auto handle = _findfirst((path + "/*.*").c_str(), &data);
    if (handle == -1) {
    	PRINTF("can not read file!");
        return;
    }
    do {
        string s = data.name;
        if (data.attrib & _A_SUBDIR) {
            //PRINTF("dir: %s\n", s.c_str());
        }
        else {
            string s1 = "." + type;
            if (s.rfind(s1) == s.size() - s1.size()) {
                files.push_back(path + "/" + s);
            }
        }
    } while (_findnext(handle, &data) == 0);
    _findclose(handle);
}
  1. 文件排序
string SplitPath(string fullPath)
{
    char szDrive[MAX_PATH] = {0};
    char szDir[MAX_PATH] = {0};
    char szFileName[MAX_PATH] = {0};
    char szExt[MAX_PATH] = {0};
    _splitpath(fullPath.c_str(), szDrive, szDir, szFileName, szExt);
    return string(szFileName);
}

bool SortEx(string x,  string y)
{
    int s1, s2;
    s1 = atoi(SplitPath(x).c_str());
    s2 = atoi(SplitPath(y).c_str());
    return s1 < s2;
}
  1. 文件合并
  int makeOut(void) {
    char type[10] = "txt";
	char curPath[128];
	vector<string> fileNames;
	static char s_cBuf[1024*1024];
	
	getcwd(curPath, sizeof(curPath));

	/* search file */
    ForeachFile(curPath, type, fileNames);
    sort(fileNames.begin(),fileNames.end(), SortEx);

    /* make output */
	if (fileNames.size() > 0) {
	    FILE *fOut;
		fOut = fopen("Out.txt","wb");
		/* Find files of the same type */
	    for (auto f : fileNames) {
	    	FILE *fIn;
	    	if (fopen(f.c_str(), "wb") == NULL) {
				PRINTF("Open input file failed, aborting...\n");
			}

	    	fseek(fIn, 0L, SEEK_END);
	    	fread(s_cBuf, sizeof(char), ftell(fIn), fIn );
			fwrite(s_cBuf, sizeof(char), 1, fOut);

			fclose(fIn);
			PRINTF("%s\n", f.c_str());
		}
		fclose(fOut);
	}
	return 0;
}
  1. 测试脚本
# -*- coding:utf-8 -*-
import os

fileSize = int(input('Input file size(MB):'))
fileNum  = int(input('Input file number:'))

for n in range(fileNum):        
    filename = str(n) + '.bin'
    f = open('.\\' + filename, 'w')

    for i in range(fileSize):
        for j in range(1024):
            try:
                f.write('01' * 512)
            except KeyboardInterrupt:
                print('\n KeyboardInterrupt')
                f.close()
                exit(-1)
    f.close()

  1. 注意事项:
  • 文件合并只针对二进制文件,其他文件类型可根据实际情况调整代码;
  • 如果文件大小超过2G,合并文件的操作并不使用,还需使用另外的操作);
  • 完整代码请参考文件合并
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风尘时光清

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值