F
F
fuzz02015-09-20 15:32:50
C++ / C#
fuzz0, 2015-09-20 15:32:50

Why is data not written to vector?

The program reads all files from the folder passed in the argument, and if the contents of the file are correct (there must be only one integer in the file), then it displays the file name and number. Validation is done using check(). All logic is in file_handle()order to try to process files in multiple threads. If it check()returns false, then I try to throw the name of the "bad" file into a vector, but this vector is always empty. What could be the problem? Thank you.

#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("*[-[:digit:]]**", 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"));
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2015-09-20
@fuzz0

The vector is not thread safe. It's surprising that your solution doesn't segfault.

D
Dmitry, 2015-11-14
@mezastel

Alternatively, try to always use the `vector<>` `concurrent_hash_map<>` from Threading Building Blocks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question