C++ Util

1.删除非空文件夹

#include <stdio.h>
#include <io.h>
#include <string.h>
#include <direct.h>
//删除文件夹目录(非空) 
int  removeDir(const char*  dirPath)
{
	struct _finddata_t fb;   //查找相同属性文件的存储结构体
	char  path[250];
	intptr_t    handle;
	int  resultone;
	int   noFile;            //对系统隐藏文件的处理标记

	noFile = 0;
	handle = 0;


	//制作路径
	strcpy(path, dirPath);
	strcat(path, "/*");

	handle = _findfirst(path, &fb);
	//找到第一个匹配的文件
	if (handle != 0)
	{
		//当可以继续找到匹配的文件,继续执行
		while (0 == _findnext(handle, &fb))
		{
			//windows下,常有个系统文件,名为“..”,对它不做处理
			noFile = strcmp(fb.name, "..");

			if (0 != noFile)
			{
				//制作完整路径
				memset(path, 0, sizeof(path));
				strcpy(path, dirPath);
				strcat(path, "/");
				strcat(path, fb.name);
				//属性值为16,则说明是文件夹,迭代
				if (fb.attrib == 16)
				{
					removeDir(path);
				}
				//非文件夹的文件,直接删除。对文件属性值的情况没做详细调查,可能还有其他情况。
				else
				{
					remove(path);
				}
			}
		}
		//关闭文件夹,只有关闭了才能删除。找这个函数找了很久,标准c中用的是closedir
		//经验介绍:一般产生Handle的函数执行后,都要进行关闭的动作。
		_findclose(handle);
	}
	//移除文件夹 , 此时为空文件夹
	//resultone = removeD(dirPath);
	resultone = RemoveDirectory(dirPath);
	return  resultone;
}

2.获取文件夹下的所有文件

tail 表示 标识已某某结尾的文件 例如 ".jpg", 两个 vector 分别表示文件的整体路径,和文件的名字

void getFiles(string path, vector<string>& files, vector<string>& filenames, const string & tail)
{
	//文件句柄  
	intptr_t 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)
				{
					getFiles(p.assign(path).append("\\").append(fileinfo.name), files, filenames, tail);
				}

			}
			else
			{
				string filename = fileinfo.name;
				size_t found = filename.find(tail);
				if (found != string::npos)
				{
					files.push_back(p.assign(path).append("\\").append(filename));
					filenames.push_back(filename);
				}
			}
		} while (_findnext(hFile, &fileinfo) == 0);

		_findclose(hFile);
	}
}

3.字符串 转换为 数

template <class Type>
Type stringToNum(const string& str)
{
	istringstream iss(str);
	Type num;
	iss >> num;
	return num;
}

4.字符串 分割

void  splitString(const string& s, vector<string>& v, const string& c)
{
	string::size_type pos1, pos2;
	pos2 = s.find(c);
	pos1 = 0;
	while (string::npos != pos2)
	{
		v.push_back(s.substr(pos1, pos2 - pos1));
		pos1 = pos2 + c.size();
		pos2 = s.find(c, pos1);
	}
	if (pos1 != s.length()) {
		v.push_back(s.substr(pos1));
	}
}

5.清除文件内容

void DataPrepareUtil::clearFileData(string filePath)
{
	if (filePath == "")
	{
		return;
	}
	ofstream in;
	in.open(filePath, ios::trunc);
	in.close();
}

6.写入文件

void DataPrepareUtil::writeDatatoFile(std::string filePath, vector<LandMark> & data, int landmark)
{
	if (filePath == "" || data.size() == 0)
	{
		return;
	}
	ofstream in;
	in.open(filePath, ios::app);
	int length = data.size();
	for (int i = 0; i < length; i++)
	{
		string dataline = data[i].fileName;
		dataline.append(" ");
		for (int j = 0; j < landmark; j++)
		{
			dataline.append(to_string(data[i].points[j].x));
			dataline.append(" ");
			dataline.append(to_string(data[i].points[j].y));
			if (j != (landmark - 1))
			{
				dataline.append(" ");
			}
			//cout.precision(20);
			//cout << "double x:" << data[i].points[j].x << endl;
			//cout.precision(20); // 设置输出精度
			//cout << "to_string():" << doubleToString(data[i].points[j].x)<<endl;
		}
		in << dataline << "\n";
	}
	in.close();
}

7.读出文件

//vector<Landmark> 使用 函数参数引用 高效一些
vector<LandMark> DataPrepareUtil::readPointVisibleData(string filePath, int numMark, int count)
{
	vector<LandMark> result;
	ifstream fileA(filePath);
	if (!fileA)
	{
		cout << "没有找到需要读取的  " << filePath << " 请将文件放到指定位置再次运行本程序。" << endl << "  按任意键以退出";
		return result;
	}
	for (int i = 0; !fileA.eof() && (i < count); i++)
	{
		LandMark mark;
		string buf;
		getline(fileA, buf, '\n');

		if (buf == "")
		{
			cout << "buf is empty." << endl;
			continue;
		}
		parsePointVisibleData(buf, mark, numMark);
		result.push_back(mark);
	}
	fileA.close();
	return result;
}

C++ 单例

//util.h文件
#ifndef  _UTIL_
#define _UTIL_

#include<iostream>
#include<map>
#include <mutex>
using namespace std;
class Singleton
{
private:
	string name; //第一个变量 拥有与 this 对象 同样的地址空间。
	int age;
	Singleton(string name, int age):name(name), age(age){}
	static Singleton *instance;
	static int num;
	std::map<string, string> mymap;
public:
	static Singleton * getInstance(string name, int age, void(*notice)());
	void readData();
	void removeMap(string key);
	void addMap(string key, string value);
	void showMap();
};



//util.cpp文件
#include "util.h"
#include <string>

using namespace std;

//必须加这两句,否者编译不通过。
Singleton* Singleton::instance = nullptr;
int Singleton::num = 1;

int static num = 2;
void * p = nullptr;
#include <mutex>
mutex mut;

condition_variable conv;

extern void notice_print();

Singleton * Singleton::getInstance(string name, int age, void (*notice)())
{
	if (instance == nullptr)
	{
		unique_lock<mutex> loc(::mut);  //持有锁 mut 其他线程在这儿会被阻塞   相当于 mut.look();
		//conv.wait(loc);  //释放锁等待被唤醒。  conv.notify_all(); 唤醒wait的线程 
		if (instance == nullptr)
		{
			instance = new Singleton(name, age);
			notice();
			notice_print();
			p = &instance->name;
			cout << " *p is :" << *((int *)p) << endl;
			cout << " *p is :" << *((char *)p) << endl;
			cout << " *p is :" << *((string *)p) << endl;
			cout << " &instance :" << instance << " &name :" << p << " &age :" << &instance->age  << " &num :" << &instance->num << " &mymay:" << &instance->mymap<< endl;
		}
		mut.unlock();
	}
	return instance;
}
void Singleton::readData()
{
	cout << "age is:" << age << " name is: " << name << "class num is :"<< num  << " global num is:" << ::num<<endl;
	cout << "&this :" << this << " &name :" << &name << endl;
}

void Singleton::removeMap(string key)
{
	if (mymap.count(key))
	{
		mymap.erase(key);
	}
}
void Singleton::addMap(string key, string value)
{
	if (!mymap.count(key))
	{
		//mymap.insert(std::pair<string, string>(key, value)); //都可以
		mymap.insert(std::make_pair(key, value));
	}
	else
	{
		cout << "the key is exist." << endl;
	}
}
void Singleton::showMap()
{
	map<string, string>::iterator it;
	it = mymap.begin();

	for (it; it != mymap.end(); it++)
	{
		cout << "key is :" << it->first << "  value is:" << it->second << endl;
	}
}

C++ 线程 同步

std::mutex mtx_syn;
std::condition_variable cv_syn;
std::condition_variable cv_syn_1;
bool ready = false;
void threadA(int id) {
	while (1)
	{   //新创建的 unique_lock 对象管理 Mutex 对象 m,并尝试调用 m.lock() 对 Mutex 对象进行上锁,如果此时另外某个 unique_lock 对象已经管理了该 Mutex 对象 m,则当前线程将会被阻塞
		std::unique_lock<std::mutex> lck(mtx_syn); //lock();  出 while循环时 就自动调用 unlock() ,也可以手动调用
		while (!ready) cv_syn.wait(lck);
		// ...
		std::cout << "thread " << id << '\n';
		Sleep(500);
		cv_syn.notify_all();   //cpu 轮询执行 所有被唤醒的线程。
		cv_syn.wait(lck);
	}
	
}
void threadB(int id) {
	while (1)
	{
		std::unique_lock<std::mutex> lck(mtx_syn);
		while (!ready) cv_syn.wait(lck);
		// ...
		std::cout << "thread " << id << '\n';
		Sleep(500);
		cv_syn.notify_all();
		cv_syn.wait(lck);
	}
}

void threadC(int id) {
	while (1)
	{
		std::unique_lock<std::mutex> lck(mtx_syn);
		while (!ready) cv_syn_1.wait(lck);
		// ...
		std::cout << "thread " << id << '\n';
		Sleep(500);
		cv_syn_1.notify_all();
		cv_syn_1.wait(lck);
	}
}

void go()
{
	std::unique_lock<std::mutex> lck(mtx_syn);
	ready = true;
	cv_syn.notify_one();
}



int main()
{

//线程同步
	std::thread threads[5];
	// spawn 10 threads:
	//for (int i = 0; i<5; ++i)
	//	threads[i] = std::thread(print_id, i);
	threads[0] = std::thread(threadA, 0);
	threads[1] = std::thread(threadB, 1);
	threads[2] = std::thread(threadC, 2);
	std::cout << "2 threads ready to race...\n";
	go();                       // go!

	for (auto& th : threads) th.join();


    return 0;
}

猜你喜欢

转载自blog.csdn.net/u011808673/article/details/81177932