fuzz0
@fuzz0

Почему данные не записываются в vector?

Программа читает все файлы из переданной в аргументе папки, и если содержимое файла корректно(в файле должно быть только одно целое число), то она выводит имя файла и число. Проверка на корректность выполняется с помощью check(). Вся логика находится в file_handle() для того чтобы попытаться обрабатывать файлы в несколько потоков. Если check() возвращает false, то я пытаюсь закинуть имя "плохого" файла в вектор, но этот вектор всегда пустой получается. В чем может быть проблема? Спасибо.
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<iomanip>
#include<regex>
#include<boost/filesystem.hpp>
#include<future>
#include<thread>
#include<chrono>

using std::cout;
using std::endl;
using namespace boost::filesystem;

inline auto check(const std::string &s)
{
	std::regex reg1("[[:blank:]]*[-[:digit:]]*[[:blank:]]*", std::regex_constants::ECMAScript);
	return regex_match(s, reg1);
}

auto file_handle(directory_entry &dir,std::vector<std::string> &v)
{
	std::ifstream is;
	is.open(dir.path().string());
	std::stringstream buf;
	buf << is.rdbuf();
	auto temp = buf.str();
	if(!check(temp))
	{
		//cout <<"wrong file: "<< dir.path().filename().string() << endl;
		v.push_back(dir.path().filename().string());
		is.clear();
		is.close();
		return 0;
	}
	cout.setf(std::ios::left, std::ios::adjustfield);
	cout << std::setw(20) << dir.path().filename().string() << " : " << std::stoi(temp) << endl;
	is.clear();
	is.close();
	std::this_thread::sleep_for(std::chrono::seconds(1));
	return std::stoi(temp);
}


int main(int argc, char *argv[])
{
	setlocale(LC_ALL, "");
	int sum{};
	std::vector<std::string> vname {};

	std::ifstream file;

	if (argc < 2)
	{
		cout << "usage: prog path" << endl;
		return 1;
	}
	boost::filesystem::path p(argv[1]);
	if (!boost::filesystem::is_directory(p))
	{
		cout << "not a directory!";
		return 1;
	}
	for (auto &el : boost::filesystem::directory_iterator(p))
	{
		if (!boost::filesystem::is_directory(el))
		{
			std::future<int> result(std::async(std::launch::async,file_handle, el,vname));
			sum += result.get();
		}

	}
	cout << "Sum: " << sum << endl;
	//out << "Files with wrong input data: \n";
	cout << std::boolalpha << vname.empty() << endl;
	//boost::copy(vname, std::ostream_iterator<std::string>(cout, "\n"));
}
  • Вопрос задан
  • 317 просмотров
Решения вопроса 1
gbg
@gbg Куратор тега C++
Любые ответы на любые вопросы
Вектор не потокобезопасен. Удивительно, что ваше решение не сегфолтится.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
mezastel
@mezastel
Финансовая математика, программирование
Как вариант, попробуйте всесто `vector<>` использовать `concurrent_hash_map<>` из Threading Building Blocks.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы