Hi, I am trying to write this simple program for school where I need to convert a text file to a binary file containing the same information but in binary. Here is a sample of the text file:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
usingnamespace std;
struct salle{
int numero; //représente le numéro de la salle.
char film[128]; // représente le nom du film à l’affiche
int places; // représente les places totales de la salle
int placeReservees; // représente les places réservées dans la salle
};
void main(void)
{
salle cinema;
string nomfilm;
ifstream texte;
ofstream bin;
texte.open("films.txt");
bin.open("films.bin",ios::binary|ios::out);
if ((!texte.fail()) && (!bin.fail()))
{
texte >> cinema.numero;
texte.ignore(1);
getline(texte,nomfilm);
cinema.film = nomfilm.c_str();
texte >> cinema.places >> cinema.placeReservees;
bin.write((char*)&cinema, sizeof(salle));
while (!texte.eof())
{
texte >> cinema.numero;
texte.ignore(1);
getline(texte,nomfilm);
cinema.film = nomfilm.c_str();
texte >> cinema.places >> cinema.placeReservees;
bin.write((char*)&cinema, sizeof(salle));
}
}
else
{
cout << "Erreur d'ouverture ou de creation de fichier" << endl;
}
}
Now I get this error while compiling
cannot convert from 'const char *' to 'char [128]'
There are no conversions to array types, although there are conversions to references or pointers to arrays
You should use strcpy(char*, const char*) function to copy the contents of one char array to another:
strcpy(cinema.film, nomfilm.c_str());
Programmer is responsible to ensure that destination (the 1st parameter) were large enough to take the whole source (2nd parameter).
But what is the reason to mix c-style of char arrays and string class of C++? If cinema.film were of string type as well, the statement
cinema.film = nomfilm;
would perform correct assignment.
Binary file takes every thing as it exists like if ur putting an integer in binary file it will store in 4 bytes , and if in txt file , it will take each number as one character ,
example
if u store 123456 in binary file than it will take 4 bytes
while if u put it in txt file than it uses 6 characters
<Always keep this in mind while doing binary fileing >