textfilestream.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #if !defined(INCLUDED_STREAM_TEXTFILESTREAM_H)
00023 #define INCLUDED_STREAM_TEXTFILESTREAM_H
00024
00025 #include "itextstream.h"
00026 #include <stdio.h>
00027 #include <string>
00028
00030 class TextFileInputStream: public TextInputStream
00031 {
00032 FILE* m_file;
00033 public:
00037 TextFileInputStream (const std::string& name)
00038 {
00039 m_file = name.empty() ? 0 : fopen(name.c_str(), "rt");
00040 }
00041 ~TextFileInputStream ()
00042 {
00043 if (!failed())
00044 fclose(m_file);
00045 }
00046
00047 std::size_t size ()
00048 {
00049 std::size_t pos;
00050 std::size_t end;
00051
00052 if (failed())
00053 return 0;
00054
00055 pos = ftell(m_file);
00056 fseek(m_file, 0, SEEK_END);
00057 end = ftell(m_file);
00058 fseek(m_file, pos, SEEK_SET);
00059
00060 return end;
00061 }
00062
00063 bool failed () const
00064 {
00065 return m_file == 0;
00066 }
00067
00068 std::string getString ()
00069 {
00070 const std::size_t buffer_size = 1024;
00071 char buffer[buffer_size];
00072
00073 for (;;) {
00074 std::size_t size = read(buffer, buffer_size);
00075 if (size == 0)
00076 break;
00077 }
00078
00079 return buffer;
00080 }
00081
00082 std::size_t read (char* buffer, std::size_t length)
00083 {
00084 return fread(buffer, 1, length, m_file);
00085 }
00086 };
00087
00089 class TextFileOutputStream: public TextOutputStream
00090 {
00091 FILE* m_file;
00092 public:
00096 TextFileOutputStream (const std::string& name)
00097 {
00098 m_file = name.empty() ? 0 : fopen(name.c_str(), "wt");
00099 }
00100 ~TextFileOutputStream ()
00101 {
00102 if (!failed())
00103 fclose(m_file);
00104 }
00105
00106 bool failed () const
00107 {
00108 return m_file == 0;
00109 }
00110
00111 std::size_t write (const std::string& buffer)
00112 {
00113 return fwrite(buffer.c_str(), 1, buffer.length(), m_file);
00114 }
00115
00116 std::size_t write (const char* buffer, std::size_t length)
00117 {
00118 return fwrite(buffer, 1, length, m_file);
00119 }
00120 };
00121
00122 template<typename T>
00123 inline TextFileOutputStream& operator<< (TextFileOutputStream& ostream, const T& t)
00124 {
00125 return ostream_write(ostream, t);
00126 }
00127
00128 #endif