0

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?

  • Whenever you perform a read operation of any kind, you must always check that the read succeeded, and handle any failure somehow. –  Mar 06 '17 at 21:41
  • first question - does the file have the correct data in it? – pm100 Mar 06 '17 at 21:42
  • You cannot Serialize/Deserialize a `string` this way. – A.S.H Mar 06 '17 at 21:44
  • Related: http://stackoverflow.com/questions/6782632/using-fread-fwrite-for-stl-string-is-it-correct –  Mar 06 '17 at 21:44

1 Answers1

1

for sure this is wrong std::fwrite(&name, sizeof(name), 1, file);.

you need

std::fwrite(name.c_str(), name.length(), 1, file);
pm100
  • 48,078
  • 23
  • 82
  • 145