C++下一些常用操作的实现

string的字符串替换操作(第一个符合的)

string strFirstReplace(const string & src, const string & pattern, const string & rep)
{
	string ret = "";
	
	int pos = src.find(pattern);
	if (pos != string::npos)
	{
		if (pos + pattern.length() < src.length())
		{
			ret = src.substr(0, pos) + rep + src.substr(pos + pattern.length());
		}
		else
		{
			ret = src.substr(0, pos) + rep;
		}
	}
	return ret;
}


string的split操作

void strSplit(const string& src, const string &separate_character, vector<string> &strs)
{
	int separate_characterLen = separate_character.size();
	int lastPosition = 0, index = -1;
	while (-1 != (index = src.find(separate_character, lastPosition)))
	{
		strs.push_back(src.substr(lastPosition, index - lastPosition));
		lastPosition = index + separate_characterLen;
	}
	string lastString = src.substr(lastPosition);
	if (!lastString.empty())
		strs.push_back(lastString);
}

将int类型转换为定长的string字符串

需要包含头文件(#include <iomanip>)
string fixedLengthInt2str(const int i, const int length)
{
	ostringstream oss;
	if (i < 0)
	{
		oss << '-1';
	}

	oss << setfill('0') << setw(length) << (i < 0 ? -i : i);

	return oss.str();
}

判断文件是否存在

需要包含头文件(#include <sys/stat.h>)
bool fileExists(string filename)
{
	struct stat fileInfo;
	return stat(filename.c_str(), &fileInfo) == 0;
}

读取目录下面的所有文件(Windows)

利用windows自带的win32 API。更多的可以参考http://stackoverflow.com/questions/612097/how-can-i-get-a-list-of-files-in-a-directory-using-c-or-c

void list_dir(const string & path, vector<string> & files)
{
	WIN32_FIND_DATA fd;

	HANDLE hFind = ::FindFirstFile(path.c_str(), &fd);
	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			// filtering directory and hidden file
			if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
				!(fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN))
			{

				files.push_back(fd.cFileName);
			}
		} while (::FindNextFile(hFind, &fd));
	}
	else
	{
		cout << "Error: cannot find the first file!" << endl;
	}
	FindClose(hFind);
}

读取目录下面的所有文件(Linux)

利用linux下的"dirent.h"头文件(https://stackoverflow.com/questions/4204666/how-to-list-files-in-a-directory-in-a-c-program)

void list_dir(const string & path, vector<string> & files)
{
    DIR * dir = NULL;
    struct dirent * dir_node = NULL;
    dir = opendir(path.c_str());
    if(dir != NULL)
    {
        while((dir_node = readdir(dir)) != NULL)
        {
            files.push_back(dir_node->d_name);
        }
        closedir(dir);
    }
}


你可能感兴趣的:(C++,windows)