Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Saturday, February 12, 2011

# OOP: A file

615 ////////////////////////////////////////
616 // Program #15: A File Class
617 /////////////////////////////////////////
618
619
620 #include <stdio.h>
621
622
623 class WriteFile
624     {
625     FILE *mFile;    // File Handle
626
627     public:
628
629     WriteFile(char *filename)    // constructor create a file
630         {
631         mFile=fopen(filename,"wt");
632         }
633
634     void Write(int x)
635         {  fprintf(mFile,"%d",x); }
636
637     void Write(char ch)
638         {  fprintf(mFile,"%c",ch);  }
639
640     void Write(void)
641         {  fprintf(mFile,"\n"); }
642
643     void Write(char *s)
644         {  fprintf(mFile,"%s",s);  }
645
646     void Write(float fl)
647         {  fprintf(mFile,"%f",fl); }
648
649     void Close()
650         { fclose(mFile); }
651    
652     };
653
654
655
656 int main(void)
657     {
658     WriteFile x("One");    // Create a file One
659     WriteFile y("Two"); // Create a file Two
660
661     x.Write("Hello");  x.Write();
662     y.Write("World");  x.Write();
663
664     x.Close(); // close file after finished
665
666         // opps, I forgot to close the y file.
667
668     return 0;
669     }
670
671
672 ////////////////////////////////////////
673 // Program #16: A File Class (Destructors)
674 /////////////////////////////////////////
675
676
677 #include <stdio.h>
678
679
680 class WriteFile
681     {
682     FILE *mFile;    // File Handle
683
684     public:
685
686     WriteFile(char *filename)    // constructor create a file
687         {
688         mFile=fopen(filename,"wt");
689         }
690
691     ~WriteFile(void)
692         {
693         fclose(mFile);
694         }
695    
696
697     void Write(int x)
698         {  fprintf(mFile,"%d",x); }
699
700     void Write(char ch)
701         {  fprintf(mFile,"%c",ch);  }
702
703     void Write(void)
704         {  fprintf(mFile,"\n"); }
705
706     void Write(char *s)
707         {  fprintf(mFile,"%s",s);  }
708
709     void Write(float fl)
710         {  fprintf(mFile,"%f",fl); }
711
712     void Close()
713         { fclose(mFile); }
714    
715     };
716
717
718
719
720
721 int main(void)
722     {
723     WriteFile x("One");    // Create a file One
724     WriteFile y("Two"); // Create a file Two
725
726     x.Write("Hello");  x.Write();
727     y.Write("World");  x.Write();
728
729
730     return 0;    // destructor closes both files
731     }
732
733
734

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

No comments:

Post a Comment