Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 21.04.2010, 21:35   #1
Assemblerru
Форумчанин
 
Регистрация: 28.01.2010
Сообщений: 224
По умолчанию как описать функцию для поиска файла

есть файл с извесным расширением гдето на жеском диске как его найти
всему свое время как зиме и весне
и каждому солнцу свой неба кусок
Assemblerru вне форума Ответить с цитированием
Старый 21.04.2010, 22:06   #2
MaTBeu
Eclipse Foundation
Старожил
 
Аватар для MaTBeu
 
Регистрация: 19.09.2007
Сообщений: 2,604
По умолчанию

Когда-то писал прогу для поиска файлов. Она, конечно, не ахти, но разобраться пойдет. Вот класс для поиска.
Код:
#ifndef CSEEKERH
#define	CSEEKERH

#include <vector>
#include <windows.h>
#include <string>

#include "disk_title.h"

class CSeeker
{
public:
	CSeeker(std::string [], HWND, HWND, bool, int);
	~CSeeker();

	std::vector<std::string> Find(std::string);
	void AddDrive(std::string);					//Add drive to drive list
	void RemoveDrive(std::string);
	void SetInner(bool);						//search type including/exluding embeded folders
	void AllDrives(std::string [], int);
	void DeleteAllDrives();

private:
	bool checkDrive(std::string);				//drive checking
	void addFileToList(LPCTSTR);				//insert a founded file name to result list
	BOOL seek(LPCTSTR lpszFileName, BOOL bInnerFolders);

	std::vector<std::string> results;			//vector of founded files
	std::string sources[26];					//drive list
	int diskCount;
	bool isInner;								//embeded y/n
	HWND window;								//status bar descriptor
	HWND res;								//listbox descriptor
};

CSeeker::CSeeker(std::string Drive[], HWND h, HWND l, bool isIn, int count)
:isInner(isIn),
window(h),
res(l),
diskCount(count)
{
	for(int i = 0; i < diskCount; i++)
	if(checkDrive(Drive[i]))
		sources[i] = Drive[i];
	else
		throw "Invalid drive";
}

void CSeeker::AddDrive(std::string new_drive)
{
	//checking a drive
	if(checkDrive(new_drive))
		sources[diskCount++] = new_drive;
	else
		throw "Invalid drive";
}

void CSeeker::RemoveDrive(std::string s)
{
	for(int i = 0; i < diskCount; i++)
	{
		if(sources[i] == s)
		{
			for(int j = i; j < diskCount; j++)
				sources[i] = sources[i+1];
			diskCount--;
		}
	}
}

void CSeeker::SetInner(bool isIn)
{
	isInner = isIn;
}

//set an all drives for searching
void CSeeker::AllDrives(std::string drives[], int count)
{
	diskCount = count;
	sources->clear();
	for(int i = 0; i < count; i++)
	{
		sources[i] = drives[i];
	}
}

//clear drives list (lasts one element)
void CSeeker::DeleteAllDrives()
{
	for(int i = 1; i < diskCount; i++)
	{
		sources[i].clear();
	}
	diskCount = 1;
}

std::vector<std::string> CSeeker::Find(std::string fileName)
{
	//making path
	std::string beg_path;
	std::string separator("\\");
	results.clear();
	for(int i = 0; i < diskCount; i++)
	{
		beg_path.clear();
		beg_path += sources[i];
		beg_path += separator;
		beg_path += fileName;
		LPSTR work_path = new char[128];
		lstrcpy(work_path, beg_path.c_str());
		lstrcat(work_path, "\0");

		//beginin the search procedure
		seek(beg_path.c_str(), isInner);
	}
	
	return results;
}
BOOL CSeeker::seek(LPCTSTR lpszFileName, BOOL bInnerFolders)
{
	LPTSTR part;
	char tmp[MAX_PATH];				// temporary array
	char name[MAX_PATH];

	HANDLE hSearch = NULL;
	WIN32_FIND_DATA wfd;
	memset(&wfd, 0, sizeof(WIN32_FIND_DATA));

	//search in embeded folders for first
	if(bInnerFolders)
	{
		if(GetFullPathName(lpszFileName, MAX_PATH, tmp, &part) == 0) 
			return FALSE;
		lstrcpy(name, part);
		lstrcpy(part, "*.*");

		//if folder exists, down to it
		wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
		if (!((hSearch = FindFirstFile(tmp, &wfd)) == INVALID_HANDLE_VALUE))
			do
			{
				if (!strncmp(wfd.cFileName, ".", 1) || !strncmp(wfd.cFileName, "..", 2))            
					continue;
				if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				{
					char next[MAX_PATH];
					if(GetFullPathName(lpszFileName, MAX_PATH, next, &part) == 0) return FALSE;
					lstrcpy(part, wfd.cFileName);
					lstrcat(next, "\\");
					SetWindowText(window, next);
					lstrcat(next, name);
					
					seek(next, TRUE);
				}
			}
			while (FindNextFile(hSearch, &wfd));
			FindClose (hSearch);
	}
	if ((hSearch = FindFirstFile(lpszFileName, &wfd)) == INVALID_HANDLE_VALUE) 
		return TRUE; 
	do
	if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
	{
		char file[MAX_PATH];
		if(GetFullPathName(lpszFileName, MAX_PATH, file, &part) == 0) return FALSE;
		lstrcpy(part, wfd.cFileName);
		
		addFileToList(file);
	}
	while (FindNextFile(hSearch, &wfd));
	FindClose (hSearch);

	return TRUE;
}

void CSeeker::addFileToList(LPCTSTR lpFileName)	
{	
	std::string new_file(lpFileName);
	results.push_back(new_file);

	SendMessage(res, LB_ADDSTRING, 0, (LPARAM)lpFileName);
	SendMessage(res, WM_PAINT, 0, 0);
}

bool CSeeker::checkDrive(std::string drive)
{
	//checking a drive title
	int flag = 0;
	for(int i = 0; i < 26; i++)
	{
		if(lstrcmp(Titles[i].title, drive.c_str()) == 0)
		{
			flag = 1;
			break;
		}
	}
	if(flag)
	{
		//checking drive type (hard drives and flash drives only)
		UINT type = GetDriveType(drive.c_str());
		return type == DRIVE_REMOVABLE || type == DRIVE_FIXED ? true : false;
	}
	return false;
}
#endif
MaTBeu вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Описать функцию Alex_193 Помощь студентам 1 15.03.2010 20:42
Как вернуть значение, используя функцию поиска позиции и смещения? PARTOS Microsoft Office Excel 7 28.12.2009 12:18
Описать функцию Compare papercut Общие вопросы C/C++ 7 26.05.2009 18:54
Описать функцию Repl(A,B) Babun Общие вопросы C/C++ 6 24.05.2009 21:31
Как правильно описать функцию? аукшщ Общие вопросы C/C++ 2 19.01.2009 11:37