write and read string to binary file C++

c++ read binary file
c++ read binary file byte by byte
binary files in c
c++ read binary file into string
c++ read binary file into buffer
how to create a binary file in c++
read int from binary file c++
c++ read bytes from binary file

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

ofstream outfile("myfile.txt", ofstream::binary);
std::string text = "Text";
outfile.write((char*) &text, sizeof (string));
outfile.close();

Then, I try to read it,

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

I just cant get it to work. I am sorry, I am just desperate. Thank you!

the line

outfile.write((char*) &text, sizeof (string));

is not correct

sizeof(string) doesn't return the length of the string, it returns the sizeof the string type in bytes.

also do not cast text to char* using a C cast, you can get hold of the char* by using the appropriate member function text.c_str()

you can simply write

outfile << text;

instead.

Text Files vs Binary Files in C Programming Language, After you have opened the binary file, you can read and write a structure or seek a a file in binary mode you must add the letter b to the end of the mode string;  ostream& write(const char*, int); Reading. To read a binary file in C++ use read method. It extracts a given number of bytes from the given stream and place them into the memory, pointed to by the first parameter. If any error is occurred during reading in the file, the stream is placed in an error state, all future read operation will be failed then.

To write a std::string to a binary file, you need to save the string length first:

std::string str("whatever");
size_t size=str.size();
outfile.write(&size,sizeof(size);
outfile.write(&str[0],size);

To read it in, reverse the process, resizing the string first so you will have enough space:

std::string str;
size_t size;
infile.read(&size, sizeof(size));
str.resize(size);
infile.read(&str[0], size);

Because strings have a variable size, unless you put that size in the file you will not be able to retrieve it correctly. You could rely on the '\0' marker that is guaranteed to be at the end of a c-string or the equivalent string::c_str() call, but that is not a good idea because 1. you have to read in the string character by character checking for the null 2. a std::string can legitimately contain a null byte (although it really shouldn't because calls to c_str() are then confusing).

C Binary Files, WritingTo write a binary file in C++ use write method. Reading and writing binary file in C/C++ #include<iostream> #include<fstream> using namespace std; struct Student { int roll_no; string name; }; int main() { ofstream  string::c_str() returns a const pointer to the text in the string. string::size() returns the number of characters in the string. You don't need to concatenate the data before writing to the file, writing one then the other has the same result.

C++ Binary File I/O, that uses all 8 bits of a byte for storing the information . It is the form which can be interpreted and understood by the computer. Read/write binary files array of structs String writing using Binary Writer in C Sharp. C# program that read all directories and files on computer & it is running on and writes them to database

Should probably also use c_str() to get the char pointer too, instead of that straight crazy cast.

How do you write an object to a binary file in C++? Hi, I create a application in which I need to stored and read the string array in a Binary file and also others data type in the same binary file. My Data Fields are :-

Try this code snippet.

/* writing string into a binary file */

  fstream ifs;
  ifs.open ("c:/filename.exe", fstream::binary | fstream::in | fstream::out);

  if (ifs.is_open())
  {
   ifs.write("string to binary", strlen("string to binary")); 
   ifs.close();
  }

Here is a good example.

member function writes a given number of bytes on the given stream, starting at the position of the "put" pointer. w+ – open for reading and writing (overwrite file) a+ – open for reading and writing (append if file exists) To open a file in binary mode you must add the letter b to the end of the mode string; for example, “wb”. For the read and write modes, you can add the b, either after the plus sign – “r+b” – or before – “rb+”.

Example: Reading and Writing Binary Files in C. #include <stdio.h> int main() { char ch;  i'm trying to read a binary file (for example an executable) into a string, then write it back FileStream fs = new FileStream("C:\\tvin.exe", FileMode.Open); BinaryReader br = new BinaryReader(fs);

#include <stdlib.h> #include <stdio.h> int main(void) { result = EXIT_SUCCESS; char file_name[] = "outbut.bin"; char str[] = "This is a binary file example"; FILE  file_stream_object.write () - to write an object into the file. file_stream_object.read () - to read object from the file. In this program there are following details to be read through Employee class. Date of joining. Program to write and read an object in, from binary file using write () and read () in C++ #include <iostream> #include

This lesson demonstrates how to perform read and write operations on a binary file in C Duration: 9:57 Posted: Mar 14, 2018 Now the fwrite () function is used to write to a binary file, like so: fwrite (&myRecord, sizeof (struct record), 1, ptr); In this example, the value inside the address &myRecord which is of the

Comments
  • It looks like you're writing the string object data, but that probably doesn't write the the TEXT stored in the object. You should be using Streams in C++. The equivalent to outfile << text.
  • @Mark a quick search revealed: cplusplus.com/reference/string/string
  • Post some real, copy-pasted code, please. Assuming string is std::string, this won't compile: string *text = "Text";
  • There is a lot wrong here, in basic understanding of how C++ works. You seem like a C programmer who's trying to make C++ things work. You should stop and read a book on C++. And most importantly, realize that C++ is a different animal (one you should almost never use malloc with).
  • @BillJames - "a quick search" does not help here, as this string could be anything, not necessarily std::string.
  • This worked for me with one change. In the writing code, I changed outfile.write(&str[0],size); to outfile.write(str.c_str(),size);
  • Assuming it is std::string. The string is being used in a pretty weird way.
  • We appreciate your answer but this is a 5 year old question.