Interaction with the file system are not so easy to implement using C++, and that’s where Boost can help you. Boost contain a lot of useful libraries, and FileSystem is one I used the the most.
To build a simple example, let say that we would go through all files in a given folder and remove them with a specific extension '.bak.
First include boost FileSystem header file and I would recommend to use a namespace alias to reduce the length of your code line (typing boost::filesystem:: blahblah every time is too long !)
#include "boost/filesystem.hpp"
namespace fs = boost::filesystem;
Now we have to define the folder path and directory_iterator
fs::path outputFolder(".");
for(fs::directory_iterator it(outputFolder); it != fs::directory_iterator() ; ++it)
{
....
}
Here we iterate over files in the current directory of the program. But using a specific path string you could reach all accessible folder.
Now in the loop, using the valid directory_iterator it, you can do a lot of different things. Below I will test if extension is .bak and if true remove that file.
if(fs::extension(it.path().filename()) == ".bak")
{
fs::remove(file);
}
Now you can still rely to system command and that you don’t have to del with different FileSystem, under windows just use the system function (<stdio.h>) like : system(‘del *.bak”);
It mainly depend of your project, because adding and using Boost for using only one of those functionality may be a bad idea.
Aucun commentaire :
Enregistrer un commentaire