write and read string to binary file C++

后端 未结 7 756
暖寄归人
暖寄归人 2020-12-09 12:46

Im having problems writing string into a binary file. This is my code:

ofstream outfile(\"myfile.txt\", ofstream::binary);
std::string text = \"Text\";
outfi         


        
7条回答
  •  离开以前
    2020-12-09 13:15

    Your code is wrong wrong way you are using to write & read the file and file extension error you are trying to read text file .txt correct code

    Write to file

    std::string text = "Text";
    ofstream outfile("myfile.dat", ofstream::binary | ios::out);
    outfile.write(&text,sizeof (string));//can take type
    outfile.write(&text,sizeof (text));//can take variable name
    outfile.close();
    

    reading file

    char* buffer = (char*) malloc(sizeof(string));
    ifstream infile("myfile.dat", ifstream::binary | ios::in);    
    infile.read(buffer, sizeof (prueba));
    std::string* elem = (string*) buffer;
    cout << *elem;
    infile.close();
    

    Try This it will work

提交回复
热议问题