简体   繁体   中英

C++ fread string missing first character on console output

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?

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

you need

std::fwrite(name.c_str(), name.length(), 1, file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM