// TestForOnlyC++.cpp : 定义控制台应用程序的入口点。
//
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <windows.h>
#include<locale>
#include<io.h>
#include <codecvt>
#pragma warning(disable:4996)
using namespace std;
void getAllFiles(string path, vector<string>& files)
{
//文件句柄
intptr_t hFile = 0;
//文件信息
struct _finddata_t fileinfo; //很少用的文件信息读取结构
string p; //string类很有意思的一个赋值函数:assign(),有很多重载版本
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)
{
files.push_back(p.assign(path).append("/").append(fileinfo.name));//保存文件夹名字
getAllFiles(p.assign(path).append("/").append(fileinfo.name), files);//递归当前文件夹
}
}
else //文件处理
{
files.push_back(p.assign(path).append("/").append(fileinfo.name));//文件名
}
} while (_findnext(hFile, &fileinfo) == 0); //寻找下一个,成功返回0,否则-1
_findclose(hFile);
}
}
string UTF8ToGB(const char* str)
{
string result;
WCHAR *strSrc;
LPSTR szRes;
//获得临时变量的大小
int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
strSrc = new WCHAR[i + 1];
MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
//获得临时变量的大小
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new CHAR[i + 1];
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
delete[]strSrc;
delete[]szRes;
return result;
}
//测试
int main()
{
string DATA_DIR = "C:/Users/11865/Desktop/4";
vector<string> files;
//测试
char * DistAll = (char *) "AllFiles.txt";
getAllFiles(DATA_DIR, files);//所有文件与文件夹的路径都输出
//ofstream ofn(DistAll); //输出文件流
int size = files.size();
int FaiNum = 0;
//ofn << size << endl;
wstring s;
for (int i = 0; i < size; i++)
{
//ofn << files[i] << endl;
//cout << files[i] << endl;
string s;
ifstream inf;
inf.open(files[i]); //特别注意,这里是:// 是双斜杠喔~~ ifstream inf("d://out.txt");用这一句可以代替这两句喔,很简单有木有~~
while (getline(inf, s)) //getline(inf,s)是逐行读取inf中的文件信息
{
string str = UTF8ToGB(s.c_str()).c_str();
cout << str << endl;
}
inf.close();
}
//ofn.close();
return 0;
}
c++ txt读取中文
最新推荐文章于 2023-06-10 11:00:43 发布