I'm trying to make a file based program where a user can enter strings, and the program would save it in a .bin file in the main directory.
This is what I currently have:
#include <ostream>
#include <string>
#include <cstdio>
#include <iostream>
using std::string;
using std::cout;
class Ingredient {
private:
FILE *file;
string name;
int nmLen;
float calories;
float fat;
float carb;
float protein;
float fiber;
void writeInfo() {
nmLen = sizeof(name);
std::fseek(file, 0, SEEK_SET);
std::fwrite(&nmLen, sizeof(int), 1, file);
std::fwrite(&name, sizeof(name), 1, file);
nmLen = 0;
name = "";
}
string readInfo() {
std::fseek(file, 0, SEEK_SET);
std::fread(&nmLen, sizeof(int), 1, file);
std::fread(&name, nmLen, 1, file);
return name;
}
public:
Ingredient(const string &nm, const float &cal, const float &cb, const float &prot, const float &fib) {
file = std::fopen((nm+".bin").c_str(), "rb+");
name = nm;
calories = cal;
carb = cb;
protein = prot;
fiber = fib;
if (file == nullptr) {
file = fopen((nm+".bin").c_str(), "wb+");
writeInfo();
cout << readInfo() << "\n";
}
else {
writeInfo();
cout << readInfo() << "\n";
}
}
};
int main() {
string v1 = "Really Long String Here";
float v2 = 1.0;
float v3 = 2.0;
float v4 = 3.0;
float v5 = 4.0;
Ingredient tester(v1, v2, v3, v4, v5);
}
In the beginning of the .bin file I store an int to indicate the length or size of the string stored so when I call fread it would take the entire string. Now, just trying to test if I write strings into file, it would return it appropriately. But what I get from the console output from my constructor is this:
eally Long String Here
Note that there is indeed a blank space that should have printed the character 'R'. Is this possibly due to the fact that I'm not fseek-ing correctly?