Program Purpose: Let's say I have 300 files in a directory. I want to take all the info from every file and store it into a single output file.
Problem:
How can I iterate through the current directory to open each file one at a time, do actions, and close them? I'm using C++17.
In short:
- Have checked cppreference, stackoverflow, cplusplus, and: https://www.codingame.com/playgrounds/5659/c17-filesystem
Although I guess I'm just blanking because I can't seem to figure this out... I feel like I'm missing something obvious..
1 2 3 4 5 6 7 8 9 10 11 12 13
// 1. Set path all files are in.
//fs::path p("C:\\Users\\Tom\\Desktop\\Anti-Shop-Exploits-v2\\1.15_Data\\recipes");
// 2. Open one file at a time using directory_iterator.
std::vector<std::string> fileLines;
for (fs::directory_entry &elem : fs::directory_iterator()) {
//for ( auto &elem : fs::directory_iterator(p) ) {
// 3a. Open file and make sure it is actually open. If not, send error msg and stop program.
std::ifstream inFile(elem);
inFile.open(elem);
// ...
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void storeDataInNewFile(std::vector<std::string> &v) {
// Declare path.
fs::path filePath("C:\\Users\\Tom\\Desktop\\Anti-Shop-Exploits-v2\\1.15_Data\\recipes\\allData.json"); // Absolute (Full) Path
// Open path / output file.
std::ofstream outFile(fs::absolute(filePath));
// Make sure it is open.
// <.. code>
// Store all data from vector into output file using a loop.
constint vSize = v.size();
for (int i = 0; i < vSize; ++i) {
outFile << v[i];
}
// ...
outFile.close();
}
Apologies for the late reply! Thank you for being so detailed! I will read your full reply later today when I have the chance to work on the program! :)