]> git.saurik.com Git - wxWidgets.git/blob - src/common/textfile.cpp
Added chapter on collection and container classes to contents
[wxWidgets.git] / src / common / textfile.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: textfile.cpp
3 // Purpose: implementation of wxTextFile class
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 03.04.98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // headers
14 // ============================================================================
15
16 #ifdef __GNUG__
17 #pragma implementation "textfile.h"
18 #endif
19
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif //__BORLANDC__
25
26 #if !wxUSE_FILE
27 #undef wxUSE_TEXTFILE
28 #define wxUSE_TEXTFILE 0
29 #endif // wxUSE_FILE
30
31 #ifndef WX_PRECOMP
32 #include "wx/string.h"
33 #include "wx/intl.h"
34 #include "wx/file.h"
35 #include "wx/log.h"
36 #endif
37
38 #include "wx/textfile.h"
39
40 // ============================================================================
41 // wxTextFile class implementation
42 // ============================================================================
43
44 // ----------------------------------------------------------------------------
45 // static methods (always compiled in)
46 // ----------------------------------------------------------------------------
47
48 // default type is the native one
49 const wxTextFileType wxTextFile::typeDefault =
50 #if defined(__WINDOWS__)
51 wxTextFileType_Dos;
52 #elif defined(__UNIX__)
53 wxTextFileType_Unix;
54 #elif defined(__WXMAC__)
55 wxTextFileType_Mac;
56 #elif defined(__WXPM__)
57 wxTextFileType_Os2;
58 #else
59 wxTextFileType_None;
60 #error "wxTextFile: unsupported platform."
61 #endif
62
63 const wxChar *wxTextFile::GetEOL(wxTextFileType type)
64 {
65 switch ( type ) {
66 default:
67 wxFAIL_MSG(wxT("bad file type in wxTextFile::GetEOL."));
68 // fall through nevertheless - we must return something...
69
70 case wxTextFileType_None: return wxT("");
71 case wxTextFileType_Unix: return wxT("\n");
72 case wxTextFileType_Dos: return wxT("\r\n");
73 case wxTextFileType_Mac: return wxT("\r");
74 }
75 }
76
77 wxString wxTextFile::Translate(const wxString& text, wxTextFileType type)
78 {
79 // don't do anything if there is nothing to do
80 if ( type == wxTextFileType_None )
81 return text;
82
83 // GRG: don't do anything either if it is empty
84 if ( text.IsEmpty() )
85 return text;
86
87 wxString eol = GetEOL(type), result;
88
89 // optimization: we know that the length of the new string will be about
90 // the same as the length of the old one, so prealloc memory to aviod
91 // unnecessary relocations
92 result.Alloc(text.Len());
93
94 wxChar chLast = 0;
95 for ( const wxChar *pc = text.c_str(); *pc; pc++ )
96 {
97 wxChar ch = *pc;
98 switch ( ch ) {
99 case _T('\n'):
100 // Dos/Unix line termination
101 result += eol;
102 chLast = 0;
103 break;
104
105 case _T('\r'):
106 if ( chLast == _T('\r') ) {
107 // Mac empty line
108 result += eol;
109 }
110 else {
111 // just remember it: we don't know whether it is just "\r"
112 // or "\r\n" yet
113 chLast = _T('\r');
114 }
115 break;
116
117 default:
118 if ( chLast == _T('\r') ) {
119 // Mac line termination
120 result += eol;
121
122 // reset chLast to avoid inserting another eol before the
123 // next character
124 chLast = 0;
125 }
126
127 // add to the current line
128 result += ch;
129 }
130 }
131
132 if ( chLast ) {
133 // trailing '\r'
134 result += eol;
135 }
136
137 return result;
138 }
139
140 #if wxUSE_TEXTFILE
141
142 // ----------------------------------------------------------------------------
143 // ctors & dtor
144 // ----------------------------------------------------------------------------
145
146 wxTextFile::wxTextFile(const wxString& strFile) : m_strFile(strFile)
147 {
148 m_nCurLine = 0;
149 m_isOpened = FALSE;
150 }
151
152 wxTextFile::~wxTextFile()
153 {
154 // m_file dtor called automatically
155 }
156
157 // ----------------------------------------------------------------------------
158 // file operations
159 // ----------------------------------------------------------------------------
160
161 bool wxTextFile::Exists() const
162 {
163 return wxFile::Exists(m_strFile);
164 }
165
166 bool wxTextFile::Create(const wxString& strFile)
167 {
168 m_strFile = strFile;
169
170 return Create();
171 }
172
173 bool wxTextFile::Create()
174 {
175 // file name must be either given in ctor or in Create(const wxString&)
176 wxASSERT( !m_strFile.IsEmpty() );
177
178 // if the file already exists do nothing
179 if ( Exists() ) return FALSE;
180
181 if ( m_file.Open(m_strFile, wxFile::write) )
182 {
183 m_file.Close();
184 return TRUE;
185 }
186 else
187 {
188 return FALSE;
189 }
190 }
191
192 bool wxTextFile::Open(const wxString& strFile)
193 {
194 m_strFile = strFile;
195
196 return Open();
197 }
198
199 bool wxTextFile::Open()
200 {
201 // file name must be either given in ctor or in Open(const wxString&)
202 wxASSERT( !m_strFile.IsEmpty() );
203
204 // open file in read-only mode
205 if ( !m_file.Open(m_strFile) )
206 return FALSE;
207
208 // read file into memory
209 m_isOpened = Read();
210
211 m_file.Close();
212
213 return m_isOpened;
214 }
215
216 // analyse some lines of the file trying to guess it's type.
217 // if it fails, it assumes the native type for our platform.
218 wxTextFileType wxTextFile::GuessType() const
219 {
220 // file should be opened and we must be in it's beginning
221 wxASSERT( m_file.IsOpened() && m_file.Tell() == 0 );
222
223 // scan the file lines
224 size_t nUnix = 0, // number of '\n's alone
225 nDos = 0, // number of '\r\n'
226 nMac = 0; // number of '\r's
227
228 // we take MAX_LINES_SCAN in the beginning, middle and the end of file
229 #define MAX_LINES_SCAN (10)
230 size_t nCount = m_aLines.Count() / 3,
231 nScan = nCount > 3*MAX_LINES_SCAN ? MAX_LINES_SCAN : nCount / 3;
232
233 #define AnalyseLine(n) \
234 switch ( m_aTypes[n] ) { \
235 case wxTextFileType_Unix: nUnix++; break; \
236 case wxTextFileType_Dos: nDos++; break; \
237 case wxTextFileType_Mac: nMac++; break; \
238 default: wxFAIL_MSG(_("unknown line terminator")); \
239 }
240
241 size_t n;
242 for ( n = 0; n < nScan; n++ ) // the beginning
243 AnalyseLine(n);
244 for ( n = (nCount - nScan)/2; n < (nCount + nScan)/2; n++ )
245 AnalyseLine(n);
246 for ( n = nCount - nScan; n < nCount; n++ )
247 AnalyseLine(n);
248
249 #undef AnalyseLine
250
251 // interpret the results (FIXME far from being even 50% fool proof)
252 if ( nDos + nUnix + nMac == 0 ) {
253 // no newlines at all
254 wxLogWarning(_("'%s' is probably a binary file."), m_strFile.c_str());
255 }
256 else {
257 #define GREATER_OF(t1, t2) n##t1 == n##t2 ? typeDefault \
258 : n##t1 > n##t2 \
259 ? wxTextFileType_##t1 \
260 : wxTextFileType_##t2
261
262 // Watcom C++ doesn't seem to be able to handle the macro
263 #if !defined(__WATCOMC__)
264 if ( nDos > nUnix )
265 return GREATER_OF(Dos, Mac);
266 else if ( nDos < nUnix )
267 return GREATER_OF(Unix, Mac);
268 else {
269 // nDos == nUnix
270 return nMac > nDos ? wxTextFileType_Mac : typeDefault;
271 }
272 #endif // __WATCOMC__
273
274 #undef GREATER_OF
275 }
276
277 return typeDefault;
278 }
279
280 bool wxTextFile::Read()
281 {
282 // file should be opened and we must be in it's beginning
283 wxASSERT( m_file.IsOpened() && m_file.Tell() == 0 );
284
285 wxString str;
286 char ch, chLast = '\0';
287 char buf[1024];
288 int n, nRead;
289 do {
290 nRead = m_file.Read(buf, WXSIZEOF(buf));
291 if ( nRead == wxInvalidOffset ) {
292 // read error (error message already given in wxFile::Read)
293 return FALSE;
294 }
295
296 for ( n = 0; n < nRead; n++ ) {
297 ch = buf[n];
298 switch ( ch ) {
299 case '\n':
300 // Dos/Unix line termination
301 m_aLines.Add(str);
302 m_aTypes.Add(chLast == '\r' ? wxTextFileType_Dos
303 : wxTextFileType_Unix);
304 str.Empty();
305 chLast = '\n';
306 break;
307
308 case '\r':
309 if ( chLast == '\r' ) {
310 // Mac empty line
311 m_aLines.Add(wxEmptyString);
312 m_aTypes.Add(wxTextFileType_Mac);
313 }
314 else
315 chLast = '\r';
316 break;
317
318 default:
319 if ( chLast == '\r' ) {
320 // Mac line termination
321 m_aLines.Add(str);
322 m_aTypes.Add(wxTextFileType_Mac);
323 chLast = ch;
324 str = ch;
325 }
326 else {
327 // add to the current line
328 str += ch;
329 }
330 }
331 }
332 } while ( nRead == WXSIZEOF(buf) );
333
334 // anything in the last line?
335 if ( !str.IsEmpty() ) {
336 m_aTypes.Add(wxTextFileType_None); // no line terminator
337 m_aLines.Add(str);
338 }
339
340 return TRUE;
341 }
342
343 bool wxTextFile::Close()
344 {
345 m_aTypes.Clear();
346 m_aLines.Clear();
347 m_nCurLine = 0;
348 m_isOpened = FALSE;
349
350 return TRUE;
351 }
352
353 bool wxTextFile::Write(wxTextFileType typeNew)
354 {
355 wxTempFile fileTmp(m_strFile);
356
357 if ( !fileTmp.IsOpened() ) {
358 wxLogError(_("can't write file '%s' to disk."), m_strFile.c_str());
359 return FALSE;
360 }
361
362 size_t nCount = m_aLines.Count();
363 for ( size_t n = 0; n < nCount; n++ ) {
364 fileTmp.Write(m_aLines[n] +
365 GetEOL(typeNew == wxTextFileType_None ? m_aTypes[n]
366 : typeNew));
367 }
368
369 // replace the old file with this one
370 return fileTmp.Commit();
371 }
372
373 #endif // wxUSE_TEXTFILE
374