Home
C++ Folder, Filenames, List, Loop, Array
Firstly this requires C++ version 17 as "filesystem" only came in on this.
Visual Studio 2019 - Debug - *!ApplicationName!* Properties - C++ - Language - Select 17...
#include <iostream>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main()
{
vector<string> filenames;
for (auto & entry : fs::directory_iterator(".")) {
string y = entry.path().filename().string();
filenames.push_back(y);
}
for (string x : filenames) {
cout << x << endl;
}
}
So to explain...
#include <iostream>
#include <filesystem>
iostream allows us to write to the screen. filesystem contains the commands we gonna use
using namespace std;
namespace fs = std::filesystem;
using namespace std means we don't have to keep on typing std::string and std:: vector etc etc
namespace fs = std::filesystem not QUITE sure here but from here on in fs is the filesystem code. I tried writing std::filesystem::directory_iterator etc but no dice.
vector<string> filenames;
We create a vector which is an array that can be easily messed with rather than a fixed size array.
for (auto & entry : fs::directory_iterator(".")) {
What the & does I am not sure, something to do with pointing to actual memory rather than letting the code do the work. Auto also appears to be a cheating definition, kinda says entry is the same as the directory iterator. The directory_iterator well... iterates through the directory.
string y = entry.path().filename().string();
entry.path()... is the path, filename obvious, string obvious. The real bitchface bugger was working out how to put this together. Easy now I can see it but learning this, urgh.
filenames.push_back(y);
push_back sticks things into the vector
for (string x : filenames) {
this seems to be shorthand for "for(string x in filenames)"
Further learning leads me to the following code. Note declaring d we can declare a directory_iterator and in the loop we can declare entry as directory_entry. This helps me clear up the "auto" confusion - goddam assumptions! I've also dropped the "&" which I still need to suss.
vector<string> filenames;
fs::directory_iterator d = fs::directory_iterator(".");
for (fs::directory_entry entry : d) {
string y = entry.path().filename().string();
filenames.push_back(y);
}
for (string x : filenames) {
cout << x << endl;
}
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home