实用小函数(不断扩充),如果谁有也可以告诉我,我更新上去。

1.文件操作类

需要的头部信息

#pragma once
#include <windows.h>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <tchar.h>
using namespace std;

#ifdef UNICODE
typedef  wstring            STLString;
#else
typedef   string            STLString;
#endif

#ifdef WIN32
#ifdef UNICODE
#define DIRECTORY_SEPARATOR	L"\\"
#define DIRECTORY_SEPARATOR_C	L'\\'
#else
#define DIRECTORY_SEPARATOR	"\\"
#define DIRECTORY_SEPARATOR_C	'\\'
#endif
#else
#ifdef UNICODE
#define DIRECTORY_SEPARATOR	L"/"
#define DIRECTORY_SEPARATOR_C	L'/'
#else
#define DIRECTORY_SEPARATOR	"/"
#define DIRECTORY_SEPARATOR_C	'/'
#endif
#endif
#define  MAX_PATH_EX 512


1.1

//************************************
// Method:    FileExists
// FullName:  FileExists
// Access:    public
// Returns:   bool
// Qualifier: 检测文件是否存在,如果文件存在返回true,文件不存在返回false
// Parameter: const STLString & sFileName  -文件路径
//************************************
bool File::FileExists(const STLString& sFileName)
{
   struct __stat64 buf;  
   int iResult = _tstat64( sFileName.c_str() , &buf);
   return (0 == iResult ? true : false);
}
1.2

//************************************
// Method:    DirExists
// FullName:  DirExists
// Access:    public 
// Returns:   bool
// Qualifier: 检测路径是否存在,存在返回true,不存在返回false
// Parameter: const STLString & sFileName   -路径
//************************************
bool File::DirExists(const STLString& sFileName)
{  
   struct __stat64 buf;
   int iResult = _tstat64( sFileName.c_str() , &buf);
   if (0 == iResult) 
   {	    
       return (buf.st_mode & _S_IFDIR ? true : false);
   }
   else return false;   
}
1.3

//************************************
// Method:    GetFileList
// FullName:  GetFileList
// Access:    public 
// Returns:   void
// Qualifier: 获取指定目录下的文件列表
// Parameter: const STLString & strTargetDirectory   -目标目录
// Parameter: bool bLookInSubdirectories             -是否要查看子文件夹
// Parameter: vector<STLString> & vecstrFileList     -保存文件列表
//************************************
void File::GetFileList( const STLString& strTargetDirectory, bool bLookInSubdirectories, vector<STLString>& vecstrFileList )
{
	// Check whether target directory string is empty
	if(strTargetDirectory.compare(_T("")) == 0) return;
	
	// Remove "\\" if present at the end of the target directory
	// Then make a copy of it and use as the current search directory
	STLString strCurrentDirectory = RemoveDirectoryEnding(strTargetDirectory);

	// This data structure stores information about the file/folder that is found by any of these Win32 API functions:
	// FindFirstFile, FindFirstFileEx, or FindNextFile function
	WIN32_FIND_DATA fdDesktop = {0};

	// Check which character set is being used and allocate array of required type
#ifdef UNICODE
	wchar_t strDesktopPath[MAX_PATH_EX];
#else
	char      strDesktopPath[MAX_PATH_EX];
#endif

	// Format and copy the current directory to the character array
	// Note the addition of the wildcard *.*, which represents all files
	// 
	// Below is a list of wildcards that you can use
	// * (asterisk)			- represents zero or more characters at the current character position
	// ? (question mark)	- represents a single character
	//
	// Modify this function so that the function can take in a search pattern with wildcards and use it in the line below to find for e.g. only *.mpg files
	_stprintf_s(strDesktopPath, MAX_PATH_EX, _T("%s\\*.*"), strCurrentDirectory.c_str());

	// Finds the first file and populates the WIN32_FIND_DATA data structure with its information
	// The return value is a search handle used in subsequent calls to FindNextFile or FindClose functions
	HANDLE hDesktop = ::FindFirstFile(strDesktopPath, &fdDesktop);	

	// If an invalid handle is returned by FindFirstFile function, something went wrong, so just quit
	if(hDesktop == INVALID_HANDLE_VALUE)
	{
		return;
	}

	// Do this on the first file found and repeat for every next file found until all the required files that match the search pattern are found
	do 
	{
		// Check if a directory was found
		if(fdDesktop.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			// Reconstruct the directory path
			_stprintf_s(strDesktopPath, MAX_PATH_EX, _T("%s\\%s"), strCurrentDirectory.c_str(), fdDesktop.cFileName);

			// Get the name of the directory
			STLString strCurrentDirectoryName = GetDirectoryName(strDesktopPath);

			// If its a current (.) or previous (..) directory indicator, just skip it
			if((strCurrentDirectoryName.compare(_T(".")) == 0) || (strCurrentDirectoryName.compare(_T("..")) == 0))
			{
				continue;
			}
			// Other wise this is a sub-directory
			else
			{
				// Check whether function was called to include sub-directories in the search
				if(bLookInSubdirectories)
				{
					// If sub-directories are to be searched as well, recursively call the function again, with the target directory as the sub-directory
					GetFileList(strDesktopPath, bLookInSubdirectories, vecstrFileList);
				}
			}
		}
		// A file was found
		else 
		{
			// Reconstruct the file path
			_stprintf_s(strDesktopPath, MAX_PATH_EX, _T("%s\\%s"), strCurrentDirectory.c_str(), fdDesktop.cFileName);

			// Create a stlString for the file path
			STLString strFilePath = strDesktopPath;

			// Add the string to the vector
			vecstrFileList.push_back(strFilePath);
		}
	}
	// Search for the next file that matches the search pattern
	while(FindNextFile(hDesktop, &fdDesktop) == TRUE);

	// Close the search handle
	FindClose(hDesktop);
}
1.3.1  -1.3的辅助函数,可以单独使用

//************************************
// Method:    AddDirectoryEnding
// FullName:  AddDirectoryEnding
// Access:    public 
// Returns:   STLString
// Qualifier: Adds "\" to the end of a directory path, if not present
// Parameter: const STLString & strDirectoryPath -Target directory
//************************************
STLString File::AddDirectoryEnding( const STLString& strDirectoryPath )
{
	if(strDirectoryPath.compare(_T("")) == 0) return STLString(_T(""));
	STLString strDirectory = strDirectoryPath;
	if(strDirectory[strDirectory.length() - 1] != DIRECTORY_SEPARATOR_C)
	{
		strDirectory += DIRECTORY_SEPARATOR;
	}
	return strDirectory;
}
1.3.2 -1.3的辅助函数,可以单独使用

//************************************
// Method:    RemoveDirectoryEnding
// FullName:  RemoveDirectoryEnding
// Access:    public 
// Returns:   STLString
// Qualifier: Removes "\" from the end of a directory path, if present
// Parameter: const STLString & strDirectoryPath -Target directory
//************************************
STLString File::RemoveDirectoryEnding( const STLString& strDirectoryPath )
{
	if (strDirectoryPath.compare(_T("")) == 0) return STLString(_T(""));
	STLString strDirectory = strDirectoryPath;
	if (strDirectory[strDirectory.length() - 1] == DIRECTORY_SEPARATOR_C)
	{
		strDirectory.erase(strDirectory.length() - 1);
	}
	return strDirectory;
}
1.3.3 -1.3的辅助函数,可以单独使用

//************************************
// Method:    GetDirectoryName
// FullName:  GetDirectoryName
// Access:    public 
// Returns:   STLString
// Qualifier: Gets the name of the directory form the path: e.g. C:\Program Files\XYZ, will return XYZ
// Parameter: const STLString & strDirectoryPath  -Target directory
//************************************
STLString File::GetDirectoryName( const STLString& strDirectoryPath )
{
	if(strDirectoryPath.compare(_T("")) == 0) return STLString(_T(""));
	STLString strDirectoryName = RemoveDirectoryEnding(strDirectoryPath);
	size_t i64Index = strDirectoryName.find_last_of(DIRECTORY_SEPARATOR);
	if(i64Index == STLString::npos)
		return STLString(_T(""));
	strDirectoryName.erase(0, i64Index + 1);
	return strDirectoryName;
}

2 字符串类

2.1

//************************************
// Method:    wstring2string
// FullName:  wstring2string
// Access:    public 
// Returns:   string
// Qualifier: wstring转string
// Parameter: wstring wstr  -要转换的字符串
//************************************
std::string wstring2string(std::wstring wstr)   
{   
    std::string result; 
	//获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的   
	int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), (int)(wstr.size()), NULL, 0, NULL, NULL);   
	char* buffer = new char[len + 1];   
	//宽字节编码转换成多字节编码   
	WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), (int)(wstr.size()), buffer, len, NULL, NULL);   
	buffer[len] = '\0';   
	//删除缓冲区并返回值   
	result.append(buffer);   
	delete[] buffer; 
	return result;   
}  

2.2

//************************************
// Method:    string2wstring
// FullName:  string2wstring
// Access:    public 
// Returns:   wstring 
// Qualifier: string转wstring
// Parameter: string wstr  -要转换的字符串
//************************************

std::wstring string2wstring(std::string str)   
{   
    std::wstring result;   
    //获取缓冲区大小,并申请空间,缓冲区大小按字符计算   
    int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), (int)(str.size()), NULL, 0);   
    TCHAR* buffer = new TCHAR[len + 1];   
    //多字节编码转换成宽字节编码   
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), (int)(str.size()), buffer, len);   
    buffer[len] = '\0';             //添加字符串结尾   
    //删除缓冲区并返回值   
    result.append(buffer);   
    delete[] buffer;   
    return result;   
}

3 程序资源类

//************************************
// Method:    WriteResourceToFile
// FullName:  WriteResourceToFile
// Access:    public 
// Returns:   string
// Qualifier: 读取资源写入到磁盘文件
// Parameter: HINSTANCE hInstance   -包含资源的实例句柄
//            int idResource        -资源ID
//            TCHAR *type           -资源类型
//            const TCHAR* filename -要保存的文件名

//************************************
void WriteResourceToFile(HINSTANCE hInstance,int idResource,const TCHAR* filename,TCHAR *type)
{
	// 存取二进制资源
	HRSRC hResInfo = FindResource(hInstance, MAKEINTRESOURCE(idResource),type);
	HGLOBAL hgRes = LoadResource(hInstance, hResInfo);
	void *pvRes = LockResource(hgRes);
	DWORD cbRes = SizeofResource(hInstance, hResInfo);

	// 将二进制资源写到文件
	HANDLE hFile = CreateFile(filename, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL, 0);
	DWORD cbWritten;
	WriteFile(hFile, pvRes, cbRes, &cbWritten, 0);
	CloseHandle(hFile);
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值