0

I want to get txt files from directory with using c++. I searched in google and found "dirent.h" but I can't using this library. It gives me a C1083 fault. Here is my codes.I'm already included fstream,dirent.h vs...

ifstream fin;
string dir, filepath;
int num;
DIR *dp;
struct dirent *dirp;
struct stat filestat;

cout << "dir to get files of: " << flush;
getline(cin, dir);  

dp = opendir(dir.c_str());
if (dp == NULL)
{
    cout << "Error(" << errno << ") opening " << dir << endl;
    return errno;
}

while ((dirp = readdir(dp)))
{
    filepath = dir + "/" + dirp->d_name;


    if (stat(filepath.c_str(), &filestat)) continue;
    if (S_ISDIR(filestat.st_mode))         continue;


    fin.open(filepath.c_str());
    if (fin >> num)
        cout << filepath << ": " << num << endl;
    fin.close();
}

`

  • 1
    I don't know if you can use C++17, but if you can then you'll have access to the filesystem library in the standard library. – Rakete1111 Nov 30 '17 at 15:52
  • Have you tried looking up [C1083](https://msdn.microsoft.com/en-us/library/et4zwx34.aspx)? How are you including the corresponding headers? – vonludi Nov 30 '17 at 15:54
  • Prior to C++17, there's boost. Far easier than dirent. – MSalters Nov 30 '17 at 15:57

2 Answers2

1

what is about using boost ? For instance (to be checked):

int     filter_txt_files (std::string offset,std::vector<std::string>& vec_res)
{  
    boost::system::error_code ec;
    boost::filesystem::path offset_path(offset);

    for (boost::filesystem::directory_iterator it (offset_path, ec), eit;
         it != eit;
         it.increment (ec)
         )
    {
        if (ec)
            continue;

        if (boost::filesystem::is_regular_file (it->path ()))            
        {
            if(it->path ().extension ().string () == "txt")
                vec_res.push_back(it->path ().string());
        }
        // if you need recursion
        else if (boost::filesystem::is_directory (it->path ()))
        {
            filter_txt_files(it->path ().string(),vec_res);
        }
    }
    return ((int)vec_res.size());
}
nullptr
  • 93
  • 11
0

Function are you are using are from POSIX standard and are not implemented on Windows.

If you need portable C++ solution, the only way is to use C++17 filesystem library - but it is not implemented in Visual Studio 2015 and earlier.

Another solution is to use Boost, more precisely Boost.Filesystem library.

Both solutions do not handle wildcards, so you will have to implement filtering yourself, probably using std::regex.

You can also use native Windows API functions FindFirstFile, FindNextFile, FindClose - those support wildcards. MSDN has an example on how to use those.