FileInputStream.cpp

Go to the documentation of this file.
00001 #include <sys/types.h>
00002 #include <sys/stat.h>
00003 
00004 #include "FileInputStream.h"
00005 #include "CS240Exception.h"
00006 
00007 
00008 
00009 
00010 FileInputStream::FileInputStream(const std::string & url)
00011 {
00012     fileSize = 0;
00013     numRead = 0;
00014 
00015     ParseURL(url);
00016     OpenFile();
00017 }
00018 
00019 FileInputStream::~FileInputStream()
00020 {
00021     Close();
00022 }
00023 
00024 bool FileInputStream::IsOpen() const
00025 {
00026     return file.is_open();
00027 }
00028 
00029 bool FileInputStream::IsDone() const
00030 {
00031     return (numRead == fileSize);
00032 }
00033 
00034 char FileInputStream::Read()
00035 {
00036     if (!IsOpen())
00037         throw IllegalStateException("stream is not open");
00038     else if (IsDone())
00039         throw IllegalStateException("stream is done");
00040     else
00041     {
00042         char c;
00043         file.get(c);
00044 
00045         if (file.fail())
00046             throw FileException(std::string("error reading from file ") + fileName);
00047 
00048         ++numRead;
00049         return c;
00050     }
00051 }
00052 
00053 char FileInputStream::Peek() 
00054 {
00055     if (!IsOpen())
00056         throw IllegalStateException("stream is not open");
00057     else if (IsDone())
00058         throw IllegalStateException("stream is done");
00059     else
00060     {
00061         char c=file.peek();
00062 
00063         if (file.fail())
00064             throw FileException(std::string("error reading from file ") + fileName);
00065 
00066         return c;
00067     }
00068 }
00069 
00070 void FileInputStream::Close()
00071 {
00072     if (IsOpen())
00073         file.close();
00074 }
00075 
00076 void FileInputStream::ParseURL(const std::string & url)
00077 {
00078     const std::string prefix = "file:";
00079     fileName = url.substr(prefix.length());
00080 }
00081 
00082 void FileInputStream::OpenFile()
00083 {
00084     struct stat buf;
00085     if (stat(fileName.c_str(), &buf) < 0)
00086         throw FileException(std::string("could not determine size of file ") + fileName);
00087     fileSize = buf.st_size;
00088 
00089     file.open(fileName.c_str());
00090     if (!IsOpen() || file.fail())
00091         throw FileException(std::string("could not open file ") + fileName);
00092 }
00093 

Generated on Wed Jul 7 16:30:27 2010 for CS240Utils by  doxygen 1.5.8