#include <list>
#include <SD.h>
#define CS_PIN 5
File root;
std::list<String> indexList;
std::list<String> outList;
void setup() {
Serial.begin(115200);
Serial.print("Initializing SD card... ");
if (!SD.begin(CS_PIN)) {
Serial.println("Card initialization failed!");
while (true);
}
Serial.println("initialization done.\n");
createIndexList("FileB.txt");
evaluateFile("FileA.txt");
writeResultToFile("FileC.txt");
}
void loop() {
delay(100);
// nothing happens after setup finishes.
}
void createIndexList(String aFile){
indexList.clear();
String aLine = "";
File textFile = SD.open("/"+aFile);
if (textFile) {
Serial.println("Creating Index List from "+aFile);
while (textFile.available()) {
char c = textFile.read();
if (c >= ' ') {
aLine = aLine + c;
}
if (c == 10){
String idx = stripIndex(aLine);
if (idx > "") {
indexList.push_back(idx);
}
aLine = "";
}
}
textFile.close();
} else {
Serial.println("error opening "+aFile);
}
Serial.println();
showList();
}
String stripIndex(String Line){
int c1 = Line.indexOf(',');
int c2 = Line.indexOf(',', c1+1);
String index = "";
if (c1 >= 0 && c2 > c1){
index = Line.substring(c1+1, c2);
}
return index;
}
void showList(){
Serial.println("===== Index List ========");
for (auto idx : indexList){
Serial.println(idx);
}
Serial.println("=========================\n");
}
void evaluateFile(String aFile){
String aLine = "";
outList.clear();
File textFile = SD.open("/"+aFile);
if (textFile) {
Serial.println("Evaluating "+aFile);
Serial.println("\n======= New Entries ========");
while (textFile.available()) {
char c = textFile.read();
if (c >= ' ') {
aLine = aLine + c;
}
if (c == 10){
String idx = stripIndex(aLine);
if (idx > "") {
if (!indexFound(idx)) {
Serial.println(idx);
outList.push_back(aLine);
}
}
aLine = "";
}
}
textFile.close();
} else {
Serial.println("error opening "+aFile);
}
Serial.println("============================\n");
}
boolean indexFound(String aIndex){
boolean found = false;
for (auto ix : indexList){
if (aIndex == ix) found = true;
}
return found;
}
void writeResultToFile(String wFile){
File tFile = SD.open("/"+wFile, FILE_WRITE);
if (tFile) {
Serial.println("Writing to "+wFile);
Serial.println("\n========= Entries ========");
for (auto txt : outList){
tFile.println(txt);
Serial.println(txt);
}
tFile.close();
Serial.println("============================\n");
} else {
Serial.println("error opening "+wFile);
}
}