Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.67/9: Рейтинг темы: голосов - 9, средняя оценка - 4.67
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21

Boost search recursive Al Drewes odds with files PATH, a specificity extension

01.09.2016, 22:21. Показов 2352. Ответов 37
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Я видел этот код, ему не хватает несколько вещей, которые мне нужно Поиск файлов по расширению

нет обработки для перехвата исключений упаковывают ошибок и программы может привести к сбою ошибки.

я нужна функция, которая будет возвращать файлы путь, wstring для предоставленного расширения.

Кроме того, необходимо, чтобы пропустить поиск в конкретных трудно закодированных каталогов, например, "окна", "system32" и т.д.
например:

C
1
2
3
4
5
6
 
extension_to_search_for { ".txt",".jpg",".bmp"...}
skip_search_directories { "windows","system32"...}
wstring output = search(drive_letter, extension_to_search_for, skip_search_directories); // "c:" , ".jpg" , "windows"
 
printf("%s",output); // full path of the file
С уважением

Добавлено через 12 часов 15 минут
любой эксперт, пожалуйста, помогите мне с этим. как только я сделал я поделюсь окончательный проект со всеми вами
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
01.09.2016, 22:21
Ответы с готовыми решениями:

The path you have specified (D:\Program Files) is invalid. The Oracle Home path may not contain spaces.
Возникла проблема с установкой Oracle9i Database 9.0.1.1.1 ОС: Windows XP Professional SP3 Запускаю установщик, окно расположение...

Ошибка The specified superclass 'Navigation' contains a parse error, cannot be found on MATLAB's search path, or is shad
Здравствуйте. Пытаюсь реализовать алгоритм tangent bug, в связи с чем нашёл на гитхабе один из вариантов его реализации. При попытке...

Codeblocks. Can't find compiler executable in your configured search path's for GNU GCC COMPILER
"Can't find compiler executable in your configured search path's for GNU GCC COMPILER" вот такое вот сообщение при запуске Code Blocks....

37
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 15:03
Студворк — интернет-сервис помощи студентам
Цитата Сообщение от bornvita Посмотреть сообщение
it wont write anything to log file
Maybe you will replace your Winapi functions in FileLog with std::ofstream?
Цитата Сообщение от bornvita Посмотреть сообщение
make the main more portable
For what purpose?
You can use wstringstream to accumulate results into one wstring.
C++
1
2
3
4
5
6
7
8
#include <sstream>
 
...
 
std::wostringstream ss;
for (const auto& it : res)
  ss << it << endl;
return ss.str();
1
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 15:30  [ТС]
Well it throws error [img]http://i.**********/jc6NCKa.png[/img]
Well, it would be better if you could provide portable function as i shown you before
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 16:19
Цитата Сообщение от bornvita Посмотреть сообщение
return ss.str;
...
C++
1
return ss.str();
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
wstring func()
{
    std::wostringstream ss;
    try
    {
        auto res = search("C:\\Windows", { ".txt", ".bin" }, { "System32" });
        for (const auto& it : res)
            ss << it << endl;
    }
    catch (std::exception &ex)
    {
        cerr << ex.what() << endl;
    }
    return ss.str();
}
 
int main()
{
    wstring output = func();
}
Добавлено через 47 минут
Цитата Сообщение от bornvita Посмотреть сообщение
We have a bigger problem, just on your side use this

C++
1
auto res = search("C:\\Windows", { ".txt", ".exe" }, { "front" });
dont run in console as it cant hold large buffer for the output to show., instead use

C++
1
OutputDebugStringW(output.c_str());

it returns blank almost we hit the success and not such big depression
OutputDebugStringW. Do you really know what this function is doing?
I can say it one more time: use c++ streams for output.
1
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 16:55  [ТС]
Boost is getting to my nerves , my patience level almost 0 now. I'm almost getting torchered :<

Tried with all this:
C++
1
2
3
4
5
6
wchar_t* wc = const_cast<wchar_t*>(output.c_str());
    OutputDebugStringW(wc); // blank
    cout << "output: " << wc << endl; // output: 00B21020
 
    cout << "output2: " << output.c_str() << endl; //output2: 0117E020
                                                   //output2: 0117E020
what the heck!
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 17:15
Цитата Сообщение от bornvita Посмотреть сообщение
Boost is getting to my nerves
It not the boost's fault, but yours.
Цитата Сообщение от bornvita Посмотреть сообщение
Tried with all this:
To output widechar string you need to use... widechar stream!
C++
1
2
[B]wcout[/B] << output << endl;
[B]wcout[/B] << output.c_str() << endl;
One more time:
Цитата Сообщение от nonedark2008 Посмотреть сообщение
OutputDebugStringW. Do you really know what this function is doing?
And if you intended to use widechars you need to replace cin/cout/cerr in your code with widechar ones wcin/wcout/wcerr.
1
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 17:17  [ТС]
I was just about to answer this, saw your post on page refresh , well how will i get my output in outdebugstrng ?
C++
1
OutputDebugStringW(wc);
// assuming wc is wchar_t

The reason for this is because we need to perform some actions with the output path
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 17:26
bornvita, and for printing to file use wfstream:
C++
1
2
3
4
#include <fstream>
...
wofstream f("output.txt");
f << output << endl;
wofstream
w - means widechar
o - means output
f - means file
stream - means stream =)

Добавлено через 7 минут
Цитата Сообщение от bornvita Посмотреть сообщение
The reason for this is because we need to perform some actions with the output path
OutputDebugString is writing string into Debugger's output window. Not to the console or file - to the special window in your IDE, when debbugger is attached to your program.
1
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 17:28  [ТС]
Yes i got the concept dear, and i am using "debugView tool" which is separate portable one.

Actually i used log to just check, i need output as wchar_t ,later it will be passed to an autocode function for further graph algorithm .
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 17:35
Цитата Сообщение от bornvita Посмотреть сообщение
Yes i got the concept dear, and i am using "debugView tool" which is separate portable one
I have a non-blank output in Output window after OutputDebugStringW(result.c_str()) call, assuming the "result" wstring is not empty too.
1
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 18:19  [ТС]
Then why my output is blank in DebugView
C++
1
OutputDebugStringW(output.c_str());
Just to clarify its not my system, i installed msvs 2013 on another machine and configured boost. Still the output is blank in debugview. Just tell me how will i get the output as wchar_t !

Something like,
C++
1
wchar_t* newoutput = output
I will use the "newoutput" In messageboxw or with the autocad algo
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 18:37
Цитата Сообщение от bornvita Посмотреть сообщение
Just tell me how will i get the output as wchar_t
wstring already has wchar_t inside, just use wstring::c_str() method;
C++
1
2
wstring output = search(...);
const wchar_t *pPtr = output.c_str(); // <- Your pointer to wchar_t string is here
Добавлено через 6 минут
bornvita, if you want to have a modifiable wchar_t string instead of const one, just create a copy like this:
C++
1
2
3
4
wchar_t *pPtr = new wchar_t[output.length() + 1];
wcscpy_s(pPtr, output.length() + 1, output.c_str());
// Call to your function
delete[] pPtr;
1
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 18:52  [ТС]
How come it shows output your side, and not mine!


Добавлено через 8 минут
EDIT:

Still empty output, This is in main
C++
1
2
3
4
5
6
7
    wstring output = func();
 
    wchar_t *pPtr = new wchar_t[output.length() + 1];
    wcscpy_s(pPtr, output.length() + 1, output.c_str());
    // Call to your function
    OutputDebugStringW(pPtr);
    delete[] pPtr;
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 19:10
Цитата Сообщение от bornvita Посмотреть сообщение
How come it shows output your side, and not mine
I think DebugView just cannot handle too long strings.
Try to modify your code in this way:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
wstring func()
{
    std::wostringstream ss;
    try
    {
        auto res = search("C:\\Windows", { ".txt", ".bin" }, { "System32" });
        for (const auto& it : res) {
            ss << it << endl;
            OutputDebugStringW(it.c_str()); // <- this
        }
    }
    catch (std::exception &ex)
    {
        cerr << ex.what() << endl;
    }
    return ss.str();
}
Добавлено через 9 минут
Цитата Сообщение от nonedark2008 Посмотреть сообщение
I think DebugView just cannot handle too long strings.
I was right. No more then something around 32k widechar symbols.
Stop using debug output for some junk data. Print it to console or file.
0
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 19:17  [ТС]
Now i get output in debugview, then why not in our main() ?
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 19:21
Цитата Сообщение от bornvita Посмотреть сообщение
then why not in our main()
Read my posts carefully, pls.
1
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 19:24  [ТС]
Note: In late days i have used debugview to output 1Gb+ of raw unicode and anscii data , obviously with some small lag

Добавлено через 1 минуту
32k widechar symbols Oh ok .Ok.

So do you think if we allocate a HeapAlloc in main to hold the buffer then output to debugview, will work?
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
03.09.2016, 19:28
Цитата Сообщение от bornvita Посмотреть сообщение
So do you think if we allocate a HeapAlloc in main to hold the buffer then output to debugview, will work?
No. All you can do is to split data into smaller parts.
Цитата Сообщение от bornvita Посмотреть сообщение
1Gb+ of raw unicode
I think you hadn't have all your 1Gb of raw data in one solid std::wstring, and you printed it string by string.
1
 Аватар для bornvita
16 / 0 / 1
Регистрация: 30.08.2016
Сообщений: 21
03.09.2016, 20:16  [ТС]
Лучший ответ Сообщение было отмечено castaway как решение

Решение

oh ok , will try logging

---

yep, 500 kb at a time ,not the whole at once... good to know this new discovery by you.

Will test and report back dear

Добавлено через 36 минут
Firstly a big thanks goes to this genius "nonedark2008",He almost stood so patiently the whole day answering our kiddish questions. provided solution every single minute/seconds. Hug from me and our team.

After a long testing we found its a bug with boost (one team member confirmed it from boost forum mailing list, staff member)
Many files are skipped in search and various other problems like deadlock .

So we gave our hands up and were successful to get all files and perform other filter task using FindNextFile and it worked like a charm. So we tend to use it and our project staff also approved this.

Here is code if anyone need's it in their hard time
code is long so here: http://pastebin.com/raw/ZT46a91s

Добавлено через 8 минут
Here are the two official Win32 function's
https://msdn.microsoft.com/en-... s.85).aspx
https://msdn.microsoft.com/en-... s.85).aspx
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
03.09.2016, 20:16

Code::Blocks: "Сan't find compiler executable in your configured search path's"
Не могу настроить Code::Blocks IDE Вот такая ошибка &quot;Сan't find compiler executable in your configured search path's for Intel C/C++...

Сокращение пути к файлу, x:\path\path\...\path
Помогите с решением такой задачи, желательно до четверга)): Строка длиной не более 1000 символов содержит полный путь к файлу в формате...

Codewars. This is odds
Create a function that checks if a number is odd. Expect negative and decimal numbers too. For negative numbers, return true if its...

Как объединить 3 раздела HDD в 1 без потерь путей программ(Например с изменением с C:\Program Files на E:\Proram Files)?
Есть ли ПО для этого или это делается вручную?

Как удалить Piese Search из Google Chrome? Аналогичный Get Search
Аналогичный Get Search.


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
38
Ответ Создать тему
Новые блоги и статьи
Как установить и настроить Windows 11 без подключения к Интернету и без аккаунта Microsoft
Maks 22.11.2026
Положу сюда, чтобы не искать постоянно. • На экране «Давайте подключим вас к сети» во время установки Windows 11 нажмите комбинацию клавиш Shift+F10, чтобы открыть командную строку. Введите. . .
Транслитерация текста с кириллицы на латиницу (вариант №5)
Maks 17.11.2026
Дабы оставить позади все споры о том, какая буква каким образом должна транслитерироваться на латиницу - решил таки доработать данное решение и довести его до мало-мальски логического завершения. . . .
Просмотровщик HLP и конвертер в CHM
Argus19 16.11.2026
Просмотровщик HLP и конвертер в CHM Давно хотел переделать справку Microsoft® Win32® Programmer's Reference, чтобы иметь её под рукой. Но использовать несколько программ не удобно. Искал другие. . .
BitTorrent (версия 7.11 English) и Меню Настройки
russiannick 15.11.2026
Пункты, отвечающие за отключение обновлений в BitTorrent версии 7. 11 (английской) Options Preferences General Language
Транслитерация текста с кириллицы на латиницу (вариант №4)
Maks 15.11.2026
Что-то я перемудрил с предыдущими версиями, в этот раз сделал всё проще, обратившись к функции "СтрокаЛатиницей" из типового общего модуля "СтроковыеФункцииКлиент". В данной функции нет апострофов,. . .
BitTorrent (версия 4.3.9) и Меню Настройки
russiannick 15.11.2026
В меню Настройки можно отключить автоматическое обновление программы. Карта этого меню приложена ниже. Нужный пункт выделен красным. Сервис Настройки Поведение
Транслитерация текста с кириллицы на латиницу (вариант №3)
Maks 15.11.2026
Обновленная версия предыдущей обработки. Изменения коснулись букв: Ъ, Ы, Ь, Э, отображения которых зависят от положения реквизита "Транслитерация имён". Изменено отображение буквы Й. Добавлена. . .
Транслитерация текста с кириллицы на латиницу (вариант №2)
Maks 13.11.2026
Обновленная версия ранее созданной обработки. Добавлено: - Проверка исходного текста на кириллицу, через обращение к стандартной функции "ТолькоКириллицаВСтроке" из общего модуля. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru