// fichier.cpp Utilisations des fichiers // > lireFic: charge le contenu un fichier en mémoire // > ecrireFic: charge une chaîne vers un fichier // > deux classes d'exception // auteur: R.Astier // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + #include <iostream.h> #include <fstream.h> #include <string.h> // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + class ExcFichier { public: ExcFichier(int e) : etat(e) { } virtual string message(); protected: int etat; string msg; }; // Erreur sur fichier en lecture (entrée) class ExcFichierE : ExcFichier { public: string message() {return msg; } ; ExcFichierE(char * txt, int e): ExcFichier(e) { msg += "* * (ExcFichierE) Fichier "; (msg += txt) += " non accessible en lecture"; } }; // Erreur sur fichier en sortie ou écriture class ExcFichierS : ExcFichier { public: string message() {return msg; } ; ExcFichierS(char * txt, int e): ExcFichier(e) { msg += "* * (ExcFichierE) Fichier '"; (msg += txt) += "' ne peut pas être créé"; } private: int etat; }; string lireFic(char nomFic[]) throw (ExcFichierE) { ifstream fic(nomFic,ios::ate); if(!fic) throw ExcFichierE(nomFic, fic.rdstate()); long taille=fic.tellg(); cout << "taille de "<< nomFic << ": "<<taille << endl; // Revenir au début, lire le contenu et fermer le fichier fic.seekg(0,ios::beg); char * pmem=new char[1+taille]; fic.read(pmem,taille); pmem[taille]='\0'; fic.close(); string txt = string(pmem,taille); delete[] pmem; return txt; } void ecrireFic(string txt, char nomFic[]) throw (ExcFichierS) { ofstream fic(nomFic,ios::binary); if(!fic) throw ExcFichierS(nomFic, fic.rdstate()); fic.write(txt.c_str(),txt.length()); fic.close(); } //- - - - - - - - Q u e l q u e s u t i l i s a t i o n s - - - - -+ int main( int ntm, char *tm[]) { string txt = lireFic("fichier.cpp"); cout <<; "longueur: " <<; txt.length() <<; endl; char nom[200]; cout<<;"un nom (arrêt:fin): "; cin.getline(nom,sizeof(nom)); while(strcmp(nom,"fin") != 0) { try { txt=lireFic(nom); cout << nom <<" -> longueur: " << txt.length() << endl; ecrireFic(txt,"toto"); } catch(ExcFichierE e) { cout<<e.message(); } // Un autre fichier cout<<"un nom (arrêt:fin): "; cin.getline(nom,sizeof(nom)); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + cout<<"\n> > > "; cin.getline( new char[80],80); return 0; } //fin fichier.cpp