注:
用C++遍历文件夹参考https://www.youkuaiyun.com/gather_26/NtTaIg3sODctYmxvZwO0O0OO0O0O.html
#include"pch.h"
#include <iostream>
#include <fstream>
#include <io.h>
#include <string>
#include <vector>
using namespace std;
void getAllFiles(string path, vector<string>& files)
{
long hFile = 0; //文件句柄
struct _finddata_t fileinfo; //文件信息读取结构
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR)) //比较文件类型是否是文件夹
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
getAllFiles(p.assign(path).append("\\").append(fileinfo.name), files); //如果是文件夹,继续向下遍历
}
}
else //是文件
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name)); //是文件,将其路径加入到files集合中
}
} while (_findnext(hFile, &fileinfo) == 0); //寻找下一个,成功返回0,否则-1
_findclose(hFile);
}
}
void trans(const char *icpp, const char *ocpp)
{
fstream incpp(icpp, ios::in); //读文件
fstream outcpp(ocpp, ios::out|ios::app);//写文件
char c, flag = '\0';
while (incpp.get(c))
{
if (c == '*')
{
while (c != '\n')//如果没有指到转行符,就一直读取
incpp.get(c);
incpp.get(c);//删除空行
}
if (c == '/')
{
incpp.get(c); //读取当前字符,指向下个字符
if (c != '/'&&c != '*')
outcpp << "/" << c; //如果下一个字符不是‘/’或‘*’,则为一般除号,正常输出
else
{
if (c == '/')
{
while (c != '\n')//如果没有指到转行符,就一直读取
incpp.get(c);
incpp.get(c);
}
else //c=='*'的情况
{
while (flag != '/')
{
flag = '\0';
incpp.get(c);
if (c == '*')
incpp.get(flag); //判别/*…*/注释是否结束
}
incpp.get(c); //去掉多余空格
}
}
}
else
outcpp << c;
}
incpp.close();
outcpp.close();
}
int main()
{
const char * filePath = "F:\\智能合约代码数据\\19500contract\\src"; //所要查找的文件夹
vector<string> files; //保存文件路径信息
int size = 0; //文件个数
while (!files.empty()) //清空vector
{
files.pop_back();
}
getAllFiles(filePath, files); //递归查找文件以及文件夹,文件夹路径为filePath
size = files.size(); //包含文件个数
for (int i = 0; i < size; i++)
{
trans(files[i].c_str(), "f:\\智能合约.txt");
}
cout << size<<"完成!";
return 0;
}