samedi 27 juin 2020

Implementing RAII on a folder iteration

I wrote this code in order to loop recursively through a folder tree and list files with their size in bytes.

Since I am using winapi and there is a Handle that should be opened and closed, I should implement RAII on this code, the problem is the examples given in online forums (not to mention that I am not a native English speaker) and many books including Effective C++ are way over the head of a person who isn't finding any place to get experience.

Anyone kind enough to point me at least?

#include <iostream>
#include <string>
#include <windows.h>

void findFiles(std::string & spath) {

  size_t i = 1;
  WIN32_FIND_DATA FindFileData;

  std::string sourcepath = spath + std::string("\\*.*");

  HANDLE hFind = FindFirstFile(sourcepath.c_str(), & FindFileData);

  if (hFind != INVALID_HANDLE_VALUE)
    do {
      std::string fullpath = std::string(spath) + std::string("\\") + std::string(FindFileData.cFileName);

      if ( * (fullpath.rbegin()) == '.')
        continue;
      else
      if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        findFiles(fullpath);
      else

        std::cout << i++ << "-" << FindFileData.cFileName << " " << (FindFileData.nFileSizeHigh *(MAXWORD + 1)) + FindFileData.nFileSizeLow << std::endl;

    } while (FindNextFile(hFind, & FindFileData));

  FindClose(hFind);

}

int main(int argc, char ** argv) {

  std::string spath(argv[1]);

  findFiles(spath);

}

Aucun commentaire:

Enregistrer un commentaire