0

Here's some code that represnts a part of what my bigger program should do. It runs absolutely fine.

However, when I change the types of variables inside of book from int to string and write strings instead of numbers there, Visual Studio takes me to the xmemory page where it says "Write access violation".

#include <fstream>
#include <string>
#include <iostream>
    
using namespace std;
    
struct book
{
    int name, author;
};

int main()
{
    setlocale(LC_ALL, ".866");
    book var;
    var.author = 1;
    var.name = 2;
    
    ofstream outFile;
    outFile.open("file.bin", ios::binary);
    outFile.write((char*)&var, sizeof(book));
    outFile.close();

    book newVar;

    ifstream inFile;
    inFile.open("file.bin", ios::binary);
    inFile.read((char*)&newVar, sizeof(book));
    inFile.close();

    cout << newVar.name;
}

Why is this and how to fix that for string? I think I have missed something very basic and very important

Swif
  • 7
  • 2
  • 2
    Don't put the fake code that works, put the code you're having trouble with. that being said the reason why it doesn't work with std::string is because they are not simple, trivially copyable objects. Strings are heap allocated. In other words, they have a pointer to memory, and you're saving the pointer, not what it points to. – Taekahn Apr 18 '22 at 19:55
  • Check out [How to write std::string to file?](https://stackoverflow.com/q/15388041/10077) – Fred Larson Apr 18 '22 at 19:58
  • It is a bad idea to write objects to files like this. It is unlikely to work consistently across machines. Look up serialization. You need to serialize your object to a stream then deserialize it out of the stream. – Martin York Apr 18 '22 at 20:05
  • If you had `name` and `author` as `std::string` this `outFile.write((char*)&var, sizeof(book));` would write invalid data to the file. A std::string allocates memory in a block using new and has a pointer that points to the allocated string. Here you save that pointer but not the data that it points to. – drescherjm Apr 18 '22 at 20:20
  • Okay now it works, thank you all – Swif Apr 19 '22 at 06:58

0 Answers0