c++ 遍历目录及子目录下所有txt文件,将其它合并到一个文件中输出

// TextCom.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "TextCom.h"
#include <vector>
#include <io.h>
#include<iostream>
#include<fstream>
#include<cstdlib>
#include <time.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

void getFiles(string path, vector<string>& files, string postfix)
{
	//文件句柄   
	long   hFile = 0;

	//文件信息    
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).c_str(), &fileinfo)) != -1)
	{
		do
		{
			//如果是目录,迭代之    
			//如果不是,加入列表   
			if ((fileinfo.attrib &  _A_SUBDIR))
			{

				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) {
					if (0==files.size()) {
						//std::cout << "-->" << (p.assign(path).append("\\*")).c_str() << endl;
						getFiles(p.assign(path).append("\\*"), files, postfix);

					}
					else
					{						
						string dirp = p.assign(path);
						dirp = dirp.replace(dirp.find("*"), 1, fileinfo.name);
						dirp = dirp.append("\\*");
						//std::cout << "-->" << (p.assign(dirp)).c_str() << endl;
						getFiles(p.assign(dirp), files, postfix);
					}
								
				}
					

			}
			else
			{
				if (postfix.size() == 0 || (postfix.size() > 0 && strstr(postfix.c_str(), strchr(fileinfo.name, '.')))) {	
					string npath = path;
					string abspath = npath.replace(npath.find("*"), 1, p.assign(fileinfo.name));
					//printf("%s\n", abspath.c_str());
					files.push_back(p.assign(abspath));
				}

				
					
					
			}

		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);

	}

}

bool fileCombine(const char* infliPath,const  char* outfilePath) {
	
	ofstream outfile(outfilePath, ios::out);//定义输出文件流对象,并赋初值,指定模式
	ifstream infile;//定义一个输入文件流对象
	char c;//用来暂存从文件独处的一个字符

	infile.open(infliPath, ios::in);
	if (!infile) {
		cerr << "打开文件 " << infliPath << " 失败" << endl;
		return false;
	}
	while (infile.get(c)) {
		outfile << c;
	}
	outfile << endl;
	infile.close();
	cout << infliPath << "--已经合并到目标文件--"<< infliPath << endl;
	outfile.close();
	return true;
}
int fileCombine2(const char* fn_in, const  char* fn_out) {
	int total = 0;//读入的整数个数
	ifstream srcFile(fn_in, ios::binary|ios::in); //以文本模式打开in.txt备读
	if (!srcFile) { //打开失败
		cout << "error opening source file." << endl;
		return 0;
	}
	ofstream destFile(fn_out, ios::binary|ios::out|ios::app); //以文本模式打开out.txt备写
	if (!destFile) {
		srcFile.close(); //程序结束前不能忘记关闭以前打开过的文件
		cout << "error opening destination file." << endl;
		return 0;
	}
	

	srcFile.seekg(0, srcFile.end);   //追溯到流的尾部
	int length = srcFile.tellg();  //获取流的长度
	srcFile.seekg(0, srcFile.beg);  //回到流的头部
	
	//将所有内容读取到temp中
	char * temp = new char[length];
	srcFile.read(temp, length);

	//将TEMP内容写入到destFile中
	destFile.write(temp, length);

	destFile.close();
	srcFile.close();
	return 0;
}

int main()
{
    int nRetCode = 0;

    HMODULE hModule = ::GetModuleHandle(nullptr);

    if (hModule != nullptr)
    {
        // 初始化 MFC 并在失败时显示错误
        if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
        {
            // TODO: 更改错误代码以符合您的需要
            wprintf(L"错误: MFC 初始化失败\n");
            nRetCode = 1;
        }
        else
        {
            // TODO: 在此处为应用程序的行为编写代码。
			printf("输入A目录:\n");
			char Apath[MAX_PATH] = { 0 };
			std::cin >> Apath;
			//strcpy_s(Apath, MAX_PATH, "D:\\Users\\xj");
			if (PathIsDirectory(Apath)) {
				printf("%s\n", Apath);

				char tstr[MAX_PATH] = { 0 };
				sprintf_s(tstr, "%d.txt", time(NULL));
				
				
				
				vector<string> files;
				getFiles(Apath, files, ".txt|.TXT");
				for (vector<string>::const_iterator iter = files.begin(); iter != files.end(); iter++)
				{
					char infliename[MAX_PATH] = { 0 };
					strcpy_s(infliename, MAX_PATH, (*iter).c_str());
					std::cout<<"--->file-->" << infliename << " "<< tstr <<endl;
					fileCombine2(infliename, tstr);
					
				}
				
			}
			else
			{
				printf("\s\n","Not a directory");
			}

        }
    }
    else
    {
        // TODO: 更改错误代码以符合您的需要
        wprintf(L"错误: GetModuleHandle 失败\n");
        nRetCode = 1;
    }
	
	system("pause");
    return nRetCode;
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值