Every time we try to insert a record in a binary file whose fields contain text, we try to give it a fixed size using a "C-style" character array.
Why is this necessary and why can't we do it with the default data type string
?
// Aquí os dejo un ejemplo más ilustrativo:
#include <iostream>
#include <fstream>
/* "#include <string>" no lo usamos al no estar permitido introducir
en nuestro fichero cadenas de caracteres "al estilo C++". */
using namespace std;
const int LIMITE = 15;
typedef struct
{
char campoTexto[LIMITE]; // Cadena de caracteres "al estilo C".
char campoTexto2[LIMITE];
} tRegistro;
tRegistro reg;
ofstream fBin;
int main() // Solo trataremos de introducir el registro en el fichero:
{
reg = {"hola", "lector"}; // Inicializamos el registro...
fBin.open("ejemplo.dat", ios::out | ios::binary);
if (!fBin.fail() && fBin.is_open())
{
fBin.write((char *) ®, sizeof(reg));
fBin.close();
} else cout << "Se ha producido un error. Intentelo de nuevo...";
return 0;
}
In addition, I also have doubts with this sentence:
fBin.write((char *) ®, sizeof(reg));
Why do we need to pass a pointer to the memory address of our register and not the register itself?