Created load and save instruction methods in file utils.

This commit is contained in:
Andrew Lalis 2018-03-02 10:11:26 +01:00
parent e714a2fc6f
commit cfd4179664
4 changed files with 55 additions and 14 deletions

View File

@ -24,8 +24,7 @@ SOURCES += model/recipe/instruction.cpp \
model/recipe/tags/recipetag.cpp \
SQLite/sqlite3.c \
model/database/resulttable.cpp \
model/database/recipedatabase.cpp \
utils/fileutils.cpp
model/database/recipedatabase.cpp
HEADERS += model/recipe/instruction.h \
model/recipe/recipe.h \

View File

@ -3,6 +3,7 @@
#include "model/database/database.h"
#include "model/database/recipedatabase.h"
#include "utils/fileutils.h"
int main(int argc, char *argv[])
{
@ -20,7 +21,9 @@ int main(int argc, char *argv[])
RecipeDatabase recipeDB("recipes");
recipeDB.storeIngredient(Ingredient("Apple", "Fruit"));
recipeDB.storeIngredient(Ingredient("Corn", "Vegetable"));
recipeDB.executeSQL("SELECT ingredientId FROM ingredient;").printData();
recipeDB.executeSQL("SELECT * FROM ingredient;").printData();
FileUtils::saveInstruction(1, Instruction("This is some plain text with no HTML markup."));
return a.exec();
}

View File

@ -1,5 +0,0 @@
#include "fileutils.h"
fileUtils::fileUtils(){
}

View File

@ -1,11 +1,55 @@
#ifndef FILEUTILS_H
#define FILEUTILS_H
#include <QStandardPaths>
#include <QFile>
#include <QDir>
#include <QTextStream>
class fileUtils
{
public:
fileUtils();
};
#include "model/recipe/instruction.h"
#endif // FILEUTILS_H
namespace FileUtils {
QString appDataPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation)+"/.recipeDB/";
void ensureAppDataFolderExists(){
QDir folder(appDataPath);
if (!folder.exists()){
folder.mkpath(".");
}
}
void saveInstruction(int nr, Instruction instruction){
ensureAppDataFolderExists();
QString filename = appDataPath + QString::fromStdString(std::to_string(nr)) +".html";
QFile file(filename);
if (file.open(QIODevice::WriteOnly)){
QTextStream stream(&file);
stream<<instruction.getHTML().c_str()<<endl;
file.close();
} else {
fprintf(stderr, "Error opening file: %s to write instruction.\n", filename.toStdString().c_str());
}
}
Instruction loadInstruction(int nr){
QString filename = appDataPath + QString::fromStdString(std::to_string(nr)) + ".html";
QFile file(filename);
if (!file.exists()){
fprintf(stderr, "Instruction Nr: %d does not exist.\n", nr);
return Instruction();
}
if (file.open(QIODevice::ReadOnly)){
QTextStream stream(&file);
QString s = stream.readAll();
file.close();
return Instruction(s.toStdString());
} else {
fprintf(stderr, "Error opening file: %s to read instruction.\n", filename.toStdString().c_str());
return Instruction();
}
}
}
#endif // FILEUTILS_H