View Single Post
  #3 (permalink)  
Old April 18th, 2005, 07:28 AM
icopec icopec is offline
Authorized User
 
Join Date: Mar 2005
Location: Zagreb, , Croatia.
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default

/************************************************** ************
Try to learn from this, these are my 2nd excersizes, from
the subject "Object oriented programming"!
The goal was to implement "file.cpp" and "file.h" files for
the "main.cpp" program to work properly
************************************************** ************/
//main.cpp
#include <iostream>
#include <string>
bool create_file(const std::string& filename){
   file f;

   if(!f.open(filename, false))
      return false;

   while(true){
     std::string s;
     std::cin >> s;
     if("end" == s)
        break;
     if(!f.write_line(s))
        break;
     }
    f.close();
    return true;
}
void display_file(const std::string& filename){
     file f;

     if(!f.open(filename))
         return;

     std::string s;
     while(f.read_line(s))
         std::cout << s;
     f.close();
}
int main(){
     std::string filename;
     std::cin >> filename;
     filename += ".txt";

     if(create_file(filename))
          display_file(filename);

     return 0; //success
}
// file.h
class file{
     FILE* fp; //default private:
public:
     bool open(const std::string& name, bool read=true);
     void close();
     bool read_line(std::string&) const;
     bool write_line(const std::string&);
};
// file.cpp
bool file::open(const std::string& name, bool read){
     const char* mode = read ? "rt" : "wt";
     return (fp = fopen(name.c_str(), mode)) != NULL;
}
void file::close(){
     fclose(fp);
}
bool file::write_line(const std::string& line){
     bool ret = fputs(line.c_str(), fp) != EOF;
     if(ret) fputs("\n", fp);
     return ret;
}
bool file::read_line(std::string& line) const {
     char s[256];
     bool ret = fgets(s, 256, fp) != NULL;
     if(ret) line = s;
     return ret;
}
/************************************************** ************
I hope there are no mistakes in code, sorry if you find them,
because I didn't have time to run it through compiler!

greetings: icopec
from: Croatia
************************************************** ************/
Reply With Quote