How to read and write string to binary files in C++

2 Answers

0 votes
#include <iostream>
#include <fstream>
 
using namespace std;
 
int main ()
{
    const char *FILENAME = "data.bin";
    string s = "c++ programming 99999";
    size_t size = s.size();
     
    ofstream o(FILENAME, ios::binary);
 
    o.write(s.c_str(), size);
    o.close();
 
    string tmp = "";
    tmp.resize(size);
     
    ifstream i(FILENAME, ios::binary);
     
    i.read(&tmp[0], size);
    i.close();
     
    cout << tmp;
 
    return 0;
}
 
 
/*
run:
 
c++ programming 99999
 
*/

 



answered Feb 14, 2020 by avibootz
edited Feb 14, 2020 by avibootz
0 votes
#include <iostream>
#include <fstream>

using namespace std;

int main ()
{
    const char *FILENAME = "data.bin";
    string s = "c++ programming 99999";
    size_t size = s.size();
    
    ofstream o(FILENAME, ios::binary);
    o.write((char*)&size, sizeof(size));
    o.write(s.c_str(), size);
    o.close();

    string tmp = "";
    size_t tmp_size;

    ifstream i(FILENAME, ios::binary);
    i.read((char*)&tmp_size, sizeof(tmp_size));
    tmp.resize(tmp_size);
    i.read(&tmp[0], tmp_size);
    i.close();
    
    cout << tmp;

    return 0;
}


/*
run:

c++ programming 99999

*/

 



answered Feb 14, 2020 by avibootz
edited Feb 14, 2020 by avibootz

Related questions

1 answer 185 views
1 answer 165 views
1 answer 187 views
1 answer 218 views
1 answer 235 views
...