I am trying to make a small program C++
that will allow me to save information in text files like for example a file with names in a binary file, and that will allow me to read it later and get the original text, so far I can save the file, but when I read it I don't know how to get the original text, that is, I only get binary data, and I am very new to using C++
.
This is the code that allows me to write a binary file:
#include <iostream>
#include <fstream>
int main(){
//Suponiendo que ya tenemos el dato a escribir y el tamaño del bloque
std::fstream archivo_a_escribir;
archivo_a_escribir.open("archivo.dat", std::ios::out | std::ios::binary);
archivo_a_escribir.write(datos, tamaño);
//Ahora cierro el archivo
archivo_a_escribir.close();
}
And I have this code that read the file:
#include <iostream>
#include <fstream>
int main(){
std::fstream archivo_a_leer;
//Leemos el archivo
archivo_a_leer.open("archivo.dat", std::ios::in | std::ios::binary);
archivo_a_leer.seekg(0, archivo_a_leer.end);
int tamaño = archivo_a_leer.tellg();
archivo_a_leer.seekg(0, archivo_a_leer.beg);
//Para almacenar los datos
char * datos = new char[tamaño];
//Leemos el archivo
archivo_a_leer.read(datos, tamaño);
//Cerramos el archivo
archivo_a_leer.close();
//En esta parte tendría que obtener o convertir los datos en el texto original.
//Una vez que hemos terminado de trabajar con los datos, liberamos memoria
delete[] datos;
}
What I need to do is get the original text that is stored in the variable datos
, if you could help me it would be great, honestly I'm tired of searching in google
.
Assuming you write a
std::string
To load the data into a
std::string( )
, you can use one of the member function variantsassign( )
:You could also do it directly in the constructor of
std::string
:Note
The
datos binarios a texto
indicates a slight confusion on your part. From the team's point of view, it's all binary data; everything is numbers. Another thing is the interpretation of these data that we or our program do. I suggest you, for example, take a look at the ASCII Wikipedia entry .