Вылетает программа winapi
25.09.2021, 22:32. Показов 2462. Ответов 2
Вылетает программа winapi.
При нажатии на любую созданную кнопку программа вылетает.
В отладчике, названия дисков, и много чего еще из переменных, в точке вылета не создаются.
Функция diskButt.getszCaption(index)); не возвращает имя диска, точка вылета.
Я сам буду искать, но может кто что заметит.
WinMain.cpp
Кликните здесь для просмотра всего текста
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
| #define _CRT_SECURE_NO_WARNINGS
#define UNICODE
#define _UNICODE
#include <windows.h>
#include <tchar.h>
#include <string>
#include "workWithDir.h"
#include "diskInfo.h"
#include "buttonLogDisks.h"
//HINSTANCE hInstance;
#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
HWND hWnd;
TCHAR szClassName[] = _T("MyClass");
MSG msg;
WNDCLASSEX wcex;
memset(&wcex,0,sizeof(wcex));
wcex.cbSize = sizeof(wcex);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = _T("MyClass");
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex))
{
MessageBox(NULL, _T("Cannot register class"), _T("Error"), MB_OK);
return 0;
}
hWnd = CreateWindowEx(0 , szClassName, _T("ShowDir"), WS_OVERLAPPEDWINDOW, 0, 0, 600, 400, NULL, NULL, hInstance, NULL);
if(!hWnd)
{
MessageBox(NULL, _T("Cannot create main window"), _T("Error"), MB_OK);
return 0;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
HDC hDC;
PAINTSTRUCT ps;
RECT rect;
static unsigned short idButton = 0;
diskInfo dInfo;
disksButton diskButt;
WorkWithDir WorkDir;
switch(msg)
{
case WM_CREATE:
dInfo.getListLogDisks();
diskButt.setButtons(hWnd, ::GetModuleHandle(NULL));
break;
case WM_COMMAND:
if(HIWORD(wParam) == BN_CLICKED)
{
idButton = LOWORD(wParam);
if(idButton >= 2000 || idButton <= 2031)
{
int index = idButton - 2000;
wchar_t *pstr = WorkDir.pathDirectory; *pstr = 0;
wcscat(WorkDir.pathDirectory, diskButt.getszCaption(index)); [B]// Здесь вылетает.[/B]
wcscat(WorkDir.pathDirectory, _T("*.*\0"));
WorkDir.setDirectory();
}
}
break;
case WM_PAINT:
{
hDC = BeginPaint(hWnd, &ps);
// вывод каталога.
unsigned int index = 0;
int x = 70, y = 15;
int katalog = 0;
int file = 0;
while(index < WorkDir.dirfilesVec.size())
{
// имя файла.
TextOut(hDC, x, y, WorkDir.dirfilesVec[index].cFileName, 110), x += 115;
// расширение.
if(WorkDir.dirfilesVec[index].dwFileAttribute & FILE_ATTRIBUTE_DIRECTORY)
{
TextOut(hDC, x, y, _T("<dir>"), 110), x += 115;
katalog++;
}
else
{
// размер файла.
wchar_t szBuf[65] = { 0 };
static wchar_t szfSize[65] = { L' ', L'\0' };
_ui64tow(WorkDir.dirfilesVec[index].nFileSize, szBuf, 10);
int k = 0; // индекс в строке результата
int count3 = 0; // счетчик троек
std::reverse(szBuf, szBuf + wcslen(szBuf));
for (int i = 0; szBuf[i] != 0; i++)
{
if (count3 == 3) // 3 символа скопировали
{
szfSize[k++] = L' '; // добавляем пробел
count3 = 1; // начинаем считать сначала
}
else
count3++;
szfSize[k++] = szBuf[i]; // копируем очередной ненулевой символ
}
szfSize[k] = 0; // терминальный ноль
std::reverse(szfSize, szfSize + k);
TextOut(hDC, x, y, szfSize, 110), x += 115;
file++;
}
// время создания файла.
wchar_t szDataTime[65];
wsprintf(szDataTime, _T("%02d.%02d.%02d %02d:%02d"), WorkDir.dirfilesVec[index].stCreationTime.wDay, WorkDir.dirfilesVec[index].stCreationTime.wMonth,
WorkDir.dirfilesVec[index].stCreationTime.wYear, WorkDir.dirfilesVec[index].stCreationTime.wHour, WorkDir.dirfilesVec[index].stCreationTime.wMinute);
TextOut(hDC, x, y, szDataTime, 110), x += 115;
y += 25;
x = 15;
index++;
}
x = 45; wchar_t szBuf[32] = {0};
wchar_t szDir[65] = _T("Каталогов "); _itow(katalog, szBuf, 10); wcscat(szDir, szBuf); TextOut(hDC, x, y, szDir, 120), x += 120;
wchar_t szFiles[65] = _T("Файлов "); _itow(file, szBuf, 10); wcscat(szFiles, szBuf); TextOut(hDC, x, y, szFiles, 120);
EndPaint(hWnd, &ps);
break;
}
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
} |
|
diskInfo.h
Кликните здесь для просмотра всего текста
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
| #define _CRT_SECURE_NO_WARNINGS
#pragma once
//#ifndef _UNICODE
#define _UNICODE
//#endif
//#ifndef UNICODE
#define UNICODE
//#endif
#include <Windows.h>
#include <tchar.h>
#include <strsafe.h>
//#include <vector>
//#include <setupapi.h>
struct diskSpace
{
//unsigned long long lpFreeBytesAvailableToCaller;
unsigned long long lpTotalNumberOfBytes;
unsigned long long lpTotalNumberOfFreeBytes;
};
struct diskEmpty
{
BOOL diskEmptyflag;
};
struct diskType
{
UINT typeDrive;
};
class diskInfo
{
private:
TCHAR *szLogicalDrives;
TCHAR **drives;
TCHAR Buf[MAX_PATH];
//TCHAR* szretbuf;
unsigned short diskCount;
diskSpace *diskArrSpace;
diskEmpty *dEmpty;
diskType *dtype;
public:
diskInfo::diskInfo();
diskInfo::~diskInfo();
void getListLogDisks();
void getSpaceDisks();
void systemDir();
LPCTSTR getDiskType(unsigned short Ndisk);
unsigned short getQuanityDisk();
TCHAR* getNameDisk(unsigned short indexDisk);
//void freeNameDisk();
//void getTypeDrive(unsigned short i);
//void freeArrDisks();
}; |
|
diskInfo.cpp
Кликните здесь для просмотра всего текста
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
| #include "diskInfo.h"
// Конструктор.
diskInfo::diskInfo()
{
diskCount = 0;
}
// Деструктор.
diskInfo::~diskInfo()
{
delete [] diskArrSpace;
delete [] dEmpty;
for(unsigned short i = 0; i < diskCount; i++)
{
delete [] drives[i];
}
delete [] dtype;
delete [] drives;
delete [] szLogicalDrives;
}
// Функция получения количества и имен логических дисков, а также типа дисков.
void diskInfo::getListLogDisks()
{
DWORD nBufferLength = ::GetLogicalDriveStrings(0, NULL);
// Каждая такая строка закрыта двоичным нулем. Последняя строка будет закрыта двумя двоичными нулями.
szLogicalDrives = new TCHAR[nBufferLength];
DWORD dwResult = ::GetLogicalDriveStrings(nBufferLength, // размер буфера.
szLogicalDrives); // адрес буфера для записи сведений об устройствах.
diskCount = static_cast<unsigned short>(dwResult)/4;
drives = new TCHAR*[diskCount];
dtype = new diskType[diskCount];
unsigned short k = 0;
for(unsigned short i = 0; i < diskCount; i++)
{
drives[i] = new TCHAR[4];
for(unsigned short j = 0; j < 4; j++)
{
drives[i][j] = szLogicalDrives[k + j];
}
k += 4;
dtype[i].typeDrive = ::GetDriveType(drives[i]);
}
}
// Функция получения пути к системе.
void diskInfo::systemDir()
{
UINT sizePath = ::GetSystemDirectory(Buf, sizeof(Buf)/sizeof(*Buf));
}
// Функция получения размера логических дисков, флаг наличия диска.
void diskInfo::getSpaceDisks()
{
diskArrSpace = new diskSpace[diskCount];
dEmpty = new diskEmpty[diskCount];
for(unsigned short i = 0; i < diskCount; i++)
{
dEmpty[i].diskEmptyflag = ::GetDiskFreeSpaceEx(drives[i], NULL/*(PULARGE_INTEGER)&diskArrSpace[i].lpFreeBytesAvailableToCaller*/,
(PULARGE_INTEGER)&diskArrSpace[i].lpTotalNumberOfBytes, (PULARGE_INTEGER)&diskArrSpace[i].lpTotalNumberOfFreeBytes);
}
}
//void diskInfo::freeNameDisk()
//{
// delete [] szretbuf;
//}
// Функция получения количества логических дисков.
unsigned short diskInfo::getQuanityDisk()
{
return diskCount;
}
// Функция передачи имени диска.
TCHAR* diskInfo::getNameDisk(unsigned short indexDisk)
{
return drives[indexDisk];
}
// Функция получения типа диска.
LPCTSTR diskInfo::getDiskType(unsigned short Ndisk)
{
int const arraysize = 128;
static TCHAR szBuf[arraysize] = {0};
size_t cdDest = arraysize*sizeof(TCHAR);
if(dtype[Ndisk].typeDrive == DRIVE_UNKNOWN)
{
StringCbPrintf(szBuf, cdDest, _TEXT(" Тип привода не может быть определен.\0"));
}
if(dtype[Ndisk].typeDrive == DRIVE_NO_ROOT_DIR)
{
StringCbPrintf(szBuf, cdDest, _TEXT(" Корневой путь недействителен; например, по указанному пути не смонтирован том.\0"));
}
if(dtype[Ndisk].typeDrive == DRIVE_REMOVABLE)
{
StringCbPrintf(szBuf, cdDest, _TEXT(" В накопителе есть съемный носитель; например, флоппи-дисковод, флэш-накопитель или устройство чтения флеш-карт.\0"));
}
if(dtype[Ndisk].typeDrive == DRIVE_FIXED)
{
StringCbPrintf(szBuf, cdDest, _TEXT(" Привод имеет фиксированный носитель; например, жесткий диск или флешка.\0"));
}
if(dtype[Ndisk].typeDrive == DRIVE_REMOTE)
{
StringCbPrintf(szBuf, cdDest, _TEXT(" Привод является удаленным (сетевым) диском.\0"));
}
if(dtype[Ndisk].typeDrive == DRIVE_CDROM)
{
StringCbPrintf(szBuf, cdDest, _TEXT(" Это привод CD-ROM.\0"));
}
if(dtype[Ndisk].typeDrive == DRIVE_RAMDISK)
{
StringCbPrintf(szBuf, cdDest, _TEXT(" Привод представляет собой RAM-диск.\0"));
}
return szBuf;
} |
|
ButtonLogDisks.h
Кликните здесь для просмотра всего текста
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| #define _CRT_SECURE_NO_WARNINGS
#pragma once
#define _UNICODE
#define UNICODE
#include <Windows.h>
#include <shellapi.h>
#include <tchar.h>
//#include <vector>
#include <commctrl.h>
#pragma comment(lib, "comctl32.lib")
#include "diskInfo.h"
// left Задает координату x левого верхнего угла прямоугольника.
// top Задает y- координату левого верхнего угла прямоугольника.
// right Задает координату x правого нижнего угла прямоугольника.
// bottom Задает y- координату нижнего правого угла прямоугольника.
struct buttonInfo
{
HWND hButton;
TCHAR *szCaption;
UINT idButton;
RECT rcButton;
BUTTON_IMAGELIST bi;
//unsigned short numButton;
};
class disksButton
{
private:
buttonInfo bInf[32];
unsigned short index;
unsigned short nCount;
SHFILEINFO sfi;
RECT rcButtonSize;
RECT rcButtonCoord;
RECT rcImage;
UINT flagButton;
diskInfo di;
public:
disksButton();
~disksButton();
void setButtons(HWND hWndParent, HINSTANCE hInstance);
void imageForButton(unsigned short i);
UINT getIdButton(unsigned short index);
TCHAR* getszCaption(unsigned short index);
void destroyImageListButton(unsigned short i);
void getFileIco(unsigned short i);
}; |
|
ButtonLogDisks.cpp
Кликните здесь для просмотра всего текста
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
| #include "buttonLogDisks.h"
disksButton::disksButton()
{
memset(&bInf,0,sizeof(bInf[32]));
nCount = 0;
index = 0;
memset(&sfi,0,sizeof(sfi));
memset(&rcButtonSize,0,sizeof(rcButtonSize));
memset(&rcButtonCoord,0,sizeof(rcButtonCoord));
memset(&rcImage,0,sizeof(rcImage));
flagButton = 0;
}
disksButton::~disksButton()
{
do
{
delete [] bInf[index].szCaption;
} while(index < nCount);
//destroyImageListButton(nCount);
}
void disksButton::setButtons(HWND hWndParent, HINSTANCE hInstance)
{
di.getListLogDisks();
nCount = di.getQuanityDisk();
rcButtonSize.left = 0; rcButtonSize.top = 0; rcButtonSize.right = 40; rcButtonSize.bottom = 24;
rcButtonCoord.left = 5; rcButtonCoord.top = 49; rcButtonCoord.right = 0; rcButtonCoord.bottom = 0;
bInf[index].rcButton.left = rcButtonCoord.left;
bInf[index].rcButton.right = rcButtonSize.right;
bInf[index].rcButton.top = 49;
bInf[index].rcButton.bottom = 24;
rcImage.left = 5, rcImage.top = 5, rcImage.right = 24, rcImage.bottom = 19; flagButton = BUTTON_IMAGELIST_ALIGN_LEFT;
do
{
bInf[index].idButton = 2000 + index;
bInf[index].szCaption = new TCHAR[4];
_tcscpy(bInf[index].szCaption, di.getNameDisk(index));
bInf[index].hButton = CreateWindowExW(0, _T("BUTTON"), bInf[index].szCaption, BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | WS_TABSTOP,
bInf[index].rcButton.left, bInf[index].rcButton.top, bInf[index].rcButton.right, bInf[index].rcButton.bottom, hWndParent, (HMENU)bInf[index].idButton, hInstance, NULL);
index++;
bInf[index].rcButton.left = index*(rcButtonCoord.left + rcButtonSize.right) + 5;
bInf[index].rcButton.right = rcButtonSize.right;
bInf[index].rcButton.top = 49;
bInf[index].rcButton.bottom = 24;
} while(index < nCount);
}
void disksButton::imageForButton(unsigned short i)
{
bInf[i].bi.himl = ImageList_Create(GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON), ILC_MASK | ILC_COLOR32, 1, 1);
if(bInf[i].bi.himl == NULL)
MessageBox(NULL, _TEXT("ImageList, не создан!"), _TEXT("Error:"), MB_OK | MB_ICONERROR);
bInf[i].bi.margin.left = rcImage.left;
bInf[i].bi.margin.right = rcImage.right;
bInf[i].bi.margin.top = rcImage.top;
bInf[i].bi.margin.bottom = rcImage.bottom;
bInf[i].bi.uAlign = flagButton;
getFileIco(i);
ImageList_AddIcon(bInf[i].bi.himl, sfi.hIcon);
Button_SetImageList(bInf[i].hButton, &bInf[i].bi);
DestroyIcon(sfi.hIcon);
}
UINT disksButton::getIdButton(unsigned short index)
{
return bInf[index].idButton;
}
TCHAR* disksButton::getszCaption(unsigned short index)
{
return bInf[index].szCaption;
}
void disksButton::getFileIco(unsigned short i)
{
DWORD_PTR res = ::SHGetFileInfoW(di.getNameDisk(i), 0, &sfi, sizeof(sfi), SHGFI_ICON);
if(res == 0)
MessageBox(NULL, _TEXT("No icon extract!"), _TEXT("Error:"), MB_OK);
}
void disksButton::destroyImageListButton(unsigned short i)
{
BOOL success;
for(unsigned short i = 0; i < nCount; i++)
{
success = ImageList_Destroy(bInf[i].bi.himl);
if(success == FALSE)
MessageBox(NULL, _TEXT("ImageList, не уничтожен!"), _TEXT("Error:"), MB_OK | MB_ICONERROR);
}
} |
|
workWithDir.h
Кликните здесь для просмотра всего текста
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
| #pragma once
#include <vector>
class WorkWithDir
{
private:
HANDLE hFind;
WIN32_FIND_DATAW wfd;
SYSTEMTIME st;
// Структура информации о файле.
struct fileStructInfo
{
DWORD dwFileAttribute;
SYSTEMTIME stCreationTime;
SYSTEMTIME stLastAccessTime;
SYSTEMTIME stLastWriteTime;
ULONGLONG nFileSize;
DWORD dwReserved0;
WCHAR cFileName[MAX_PATH];
WCHAR cAlternateFileName[14];
};
unsigned int sizeArrfiles; // количество файлов каталоге.
unsigned int sizeArrdir; // количество каталогов в каталоге.
unsigned int dir = 0, files = 0;
unsigned int indexfile = 0, indexdir = 0; // количество файлов во временном массиве структур.
std::vector<fileStructInfo> dirVec; // Вектор структур информации о каталогах и файлах.
std::vector<fileStructInfo> filesVec; // Вектор структур информации о файлах.
public:
wchar_t pathDirectory[MAX_PATH]; // путь к каталогу.
std::vector<fileStructInfo> dirfilesVec; // Вектор структур информации о каталогах и файлах.
void createFilesArray();
void setStartDir(WCHAR *dir);
void setRootDirectory();
void getDirectory();
void setDirectory();
void upDirectory(wchar_t *pszDirPath);
void downDirectory();
//void setArrayOfFiles();
void readDirectoryInfilesArray();
LPWSTR SetFullPath(wchar_t *pszfileName);
//void printDirectory();
}; |
|
workWithDir.cpp
Кликните здесь для просмотра всего текста
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
| #define _CRT_SECURE_NO_WARNINGS
#define UNICODE
#define _UNICODE
#include <Windows.h>
#include <tchar.h>
#include <iostream>
#include <vector>
#include <string>
#include "workWithDir.h"
// Структуры информации о файле.
/*typedef struct _WIN32_FIND_DATA
{
DWORD dwFileAttributes; // атрибуты файла
FILETIME ftCreationTime; // время создания файла
FILETIME ftLastAccessTime; // время доступа
FILETIME ftLastWriteTime; // время записи
DWORD nFileSizeHigh; // размер файла (старшее слово)
DWORD nFileSizeLow; // размер файла (младшее слово)
DWORD dwReserved0; // зарезервировано
DWORD dwReserved1; // зарезервировано
TCHAR cFileName[MAX_PATH]; // имя файла
TCHAR cAlternateFileName[14]; // альтернативное имя файла
} WIN32_FIND_DATA;*/
// Вычислить размеры вектора структур файлов.
void WorkWithDir::createFilesArray()
{
sizeArrfiles = 0;
hFind = FindFirstFileW(pathDirectory, &wfd);
setlocale(LC_ALL, "");
if (INVALID_HANDLE_VALUE != hFind)
{
do
{
if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
sizeArrdir++;
else
sizeArrfiles++;
}while (NULL != FindNextFileW(hFind, &wfd));
FindClose(hFind);
}
dirVec.resize(sizeArrdir);
filesVec.resize(sizeArrfiles);
}
// установить стартовую директорию.
void WorkWithDir::setStartDir(WCHAR *dir)
{
wchar_t *pstr = pathDirectory; *pstr = 0;
wcscat(pathDirectory, dir);
wcscat(pathDirectory, L"*.*\0");
SetCurrentDirectoryW(pathDirectory);
}
// Получить текущую директорию.
void WorkWithDir::getDirectory()
{
GetCurrentDirectoryW(sizeof(pathDirectory), pathDirectory);
}
// установить текущую директорию.
void WorkWithDir::setDirectory()
{
SetCurrentDirectoryW(pathDirectory);
}
// Перейти в корневую директорию.
void WorkWithDir::setRootDirectory()
{
wchar_t *pstr = pathDirectory; pstr++ ; *pstr = 0;
wcscat(pathDirectory, L":\\*.*");
SetCurrentDirectoryW(pathDirectory);
}
// Перейти по директории в верх.
void WorkWithDir::upDirectory(wchar_t *pszDirPath)
{
wchar_t *pstr = pathDirectory + wcslen(pathDirectory); pstr = pstr - 3; *pstr = 0;
wcscat(pathDirectory, pszDirPath); wcscat(pathDirectory, L"\\*.*\0");
SetCurrentDirectoryW(pathDirectory);
}
// Перейти по директории в низ.
void WorkWithDir::downDirectory()
{
wchar_t *pstr = pathDirectory + wcslen(pathDirectory);
while(*pstr != L'\\') { --pstr; }; *pstr = 0; while(*pstr != L'\\') { --pstr; }; ++pstr; *pstr = 0;
wcscat(pathDirectory, L"*.*\0"); SetCurrentDirectoryW(pathDirectory);
}
// Прочитать содержимое директории в вектор структур, с предварительным вычислением размера вектора.
void WorkWithDir::readDirectoryInfilesArray()
{
dirfilesVec.clear();
sizeArrfiles = 0, sizeArrdir = 0;
hFind = FindFirstFile(pathDirectory, &wfd);
setlocale(LC_ALL, "");
if(INVALID_HANDLE_VALUE != hFind)
{
do
{
if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
sizeArrdir++;
else
sizeArrfiles++;
}while (NULL != FindNextFile(hFind, &wfd));
FindClose(hFind);
}
dirVec.resize(sizeArrdir);
filesVec.resize(sizeArrfiles);
//g_dirfilesVec.resize(sizeArrdir + sizeArrfiles);
indexfile = 0, indexdir = 0;
hFind = FindFirstFile(pathDirectory, &wfd);
setlocale(LC_ALL, "");
if (INVALID_HANDLE_VALUE != hFind)
{
do
{
if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
dirVec[indexdir].dwFileAttribute = wfd.dwFileAttributes;
FileTimeToSystemTime(&wfd.ftCreationTime, &dirVec[indexdir].stCreationTime);
FileTimeToSystemTime(&wfd.ftLastAccessTime, &dirVec[indexdir].stLastAccessTime);
FileTimeToSystemTime(&wfd.ftLastWriteTime, &dirVec[indexdir].stLastWriteTime);
{
dirVec[indexdir].nFileSize = (wfd.nFileSizeHigh * (MAXDWORD+1)) + wfd.nFileSizeLow;
}
dirVec[indexdir].dwReserved0 = wfd.dwReserved0;
wcscat(wcscpy(dirVec[indexdir].cFileName, wfd.cFileName), _TEXT("\0"));
wcscat(wcscpy(dirVec[indexdir].cAlternateFileName, wfd.cAlternateFileName), _TEXT("\0"));
indexdir++;
dir++;
}
else
{
filesVec[indexfile].dwFileAttribute = wfd.dwFileAttributes;
FileTimeToSystemTime(&wfd.ftCreationTime, &filesVec[indexfile].stCreationTime);
FileTimeToSystemTime(&wfd.ftLastAccessTime, &filesVec[indexfile].stLastAccessTime);
FileTimeToSystemTime(&wfd.ftLastWriteTime, &filesVec[indexfile].stLastWriteTime);
{
filesVec[indexfile].nFileSize = (wfd.nFileSizeHigh * (MAXDWORD+1)) + wfd.nFileSizeLow;
}
filesVec[indexfile].dwReserved0 = wfd.dwReserved0;
wcscat(wcscpy(filesVec[indexfile].cFileName, wfd.cFileName), _TEXT("\0"));
wcscat(wcscpy(filesVec[indexfile].cAlternateFileName, wfd.cAlternateFileName), _TEXT("\0"));
indexfile++;
files++;
}
}while (NULL != FindNextFile(hFind, &wfd));
FindClose(hFind);
}
dirVec.insert(dirVec.end(), filesVec.begin(), filesVec.end());
dirfilesVec.insert(dirfilesVec.end(), dirVec.begin(), dirVec.end());
dirVec.clear(); filesVec.clear();
} |
|
0
|