]> git.saurik.com Git - wxWidgets.git/blame - src/common/textfile.cpp
Pass length including the null-terminator to cWC2MB
[wxWidgets.git] / src / common / textfile.cpp
CommitLineData
c801d85f 1///////////////////////////////////////////////////////////////////////////////
a3a584a7 2// Name: src/common/textfile.cpp
c801d85f
KB
3// Purpose: implementation of wxTextFile class
4// Author: Vadim Zeitlin
ba7f9a90 5// Modified by:
c801d85f
KB
6// Created: 03.04.98
7// RCS-ID: $Id$
8// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
65571936 9// Licence: wxWindows licence
c801d85f
KB
10///////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// headers
14// ============================================================================
15
c801d85f
KB
16#include "wx/wxprec.h"
17
18#ifdef __BORLANDC__
a1b82138 19 #pragma hdrstop
c801d85f
KB
20#endif //__BORLANDC__
21
a3a584a7 22#if !wxUSE_FILE || !wxUSE_TEXTBUFFER
a1b82138
VZ
23 #undef wxUSE_TEXTFILE
24 #define wxUSE_TEXTFILE 0
25#endif // wxUSE_FILE
26
a3a584a7
VZ
27#if wxUSE_TEXTFILE
28
ce4169a4 29#ifndef WX_PRECOMP
68c97af3
VZ
30 #include "wx/string.h"
31 #include "wx/intl.h"
32 #include "wx/file.h"
33 #include "wx/log.h"
ce4169a4
RR
34#endif
35
a3a584a7 36#include "wx/textfile.h"
68c97af3 37#include "wx/filename.h"
dbcf443c 38#include "wx/buffer.h"
c801d85f
KB
39
40// ============================================================================
41// wxTextFile class implementation
42// ============================================================================
43
a3a584a7
VZ
44wxTextFile::wxTextFile(const wxString& strFileName)
45 : wxTextBuffer(strFileName)
a1b82138 46{
a1b82138
VZ
47}
48
c801d85f
KB
49
50// ----------------------------------------------------------------------------
51// file operations
52// ----------------------------------------------------------------------------
53
a3a584a7 54bool wxTextFile::OnExists() const
ef8d96c2 55{
a3a584a7 56 return wxFile::Exists(m_strBufferName);
ef8d96c2
VZ
57}
58
1b6dea5d 59
a3a584a7 60bool wxTextFile::OnOpen(const wxString &strBufferName, wxTextBufferOpenMode OpenMode)
1b6dea5d 61{
77f859c3
VZ
62 wxFile::OpenMode FileOpenMode;
63
64 switch ( OpenMode )
65 {
66 default:
67 wxFAIL_MSG( _T("unknown open mode in wxTextFile::Open") );
68 // fall through
27752aab 69
a3a584a7
VZ
70 case ReadAccess :
71 FileOpenMode = wxFile::read;
72 break;
77f859c3 73
a3a584a7
VZ
74 case WriteAccess :
75 FileOpenMode = wxFile::write;
76 break;
77f859c3 77 }
1b6dea5d 78
a3a584a7 79 return m_file.Open(strBufferName.c_str(), FileOpenMode);
c801d85f
KB
80}
81
c801d85f 82
a3a584a7 83bool wxTextFile::OnClose()
c801d85f 84{
a3a584a7 85 return m_file.Close();
c801d85f
KB
86}
87
a3a584a7 88
830f8f11 89bool wxTextFile::OnRead(const wxMBConv& conv)
c801d85f 90{
6594faa9
VZ
91 // file should be opened
92 wxASSERT_MSG( m_file.IsOpened(), _T("can't read closed file") );
dbcf443c
VZ
93
94 // read the entire file in memory: this is not the most efficient thing to
95 // do but there is no good way to avoid it in Unicode build because if we
96 // read the file block by block we can't convert each block to Unicode
97 // separately (the last multibyte char in the block might be only partially
98 // read and so the conversion would fail) and, as the file contents is kept
99 // in memory by wxTextFile anyhow, it shouldn't be a big problem to read
100 // the file entirely
646c7e13 101 size_t bufSize = 0,
6594faa9 102 bufPos = 0;
dbcf443c 103 char block[1024];
6594faa9
VZ
104 wxCharBuffer buf;
105
106 // first determine if the file is seekable or not and so whether we can
107 // determine its length in advance
108 wxFileOffset fileLength;
109 {
110 wxLogNull logNull;
111 fileLength = m_file.Length();
112 }
113
114 // some non-seekable files under /proc under Linux pretend that they're
115 // seekable but always return 0; others do return an error
116 const bool seekable = fileLength != wxInvalidOffset && fileLength != 0;
117 if ( seekable )
118 {
119 // we know the required length, so set the buffer size in advance
120 bufSize = fileLength;
121 if ( !buf.extend(bufSize - 1 /* it adds 1 internally */) )
122 return false;
123
124 // if the file is seekable, also check that we're at its beginning
125 wxASSERT_MSG( m_file.Tell() == 0, _T("should be at start of file") );
126 }
127
128 for ( ;; )
d9ade1df 129 {
dbcf443c 130 ssize_t nRead = m_file.Read(block, WXSIZEOF(block));
86948c99
VZ
131
132 if ( nRead == wxInvalidOffset )
d9ade1df
VS
133 {
134 // read error (error message already given in wxFile::Read)
cb719f2e 135 return false;
d9ade1df
VS
136 }
137
830f8f11 138 if ( nRead == 0 )
6594faa9
VZ
139 {
140 // if no bytes have been read, presumably this is a valid-but-empty file
141 if ( bufPos == 0 )
142 return true;
143
144 // otherwise we've finished reading the file
830f8f11 145 break;
6594faa9 146 }
86948c99 147
6594faa9
VZ
148 if ( seekable )
149 {
150 // this shouldn't happen but don't overwrite the buffer if it does
151 wxCHECK_MSG( bufPos + nRead <= bufSize, false,
152 _T("read more than file length?") );
153 }
154 else // !seekable
155 {
156 // for non-seekable files we have to allocate more memory on the go
157 if ( !buf.extend(bufPos + nRead - 1 /* it adds 1 internally */) )
158 return false;
159 }
dbcf443c
VZ
160
161 // append to the buffer
162 memcpy(buf.data() + bufPos, block, nRead);
163 bufPos += nRead;
164 }
c1981a2f 165
6594faa9
VZ
166 if ( !seekable )
167 {
168 bufSize = bufPos;
169 }
170
830f8f11 171 const wxString str(buf, conv, bufPos);
44327ff3 172
6594faa9 173 // there's no risk of this happening in ANSI build
b260e323 174#if wxUSE_UNICODE
44327ff3 175 if ( bufSize > 4 && str.empty() )
dbcf443c 176 {
abc912df 177 wxLogError(_("Failed to convert file \"%s\" to Unicode."), GetName());
dbcf443c
VZ
178 return false;
179 }
180#endif // wxUSE_UNICODE
b260e323 181
dbcf443c 182 free(buf.release()); // we don't need this memory any more
b260e323 183
86948c99 184
dbcf443c
VZ
185 // now break the buffer in lines
186
187 // last processed character, we need to know if it was a CR or not
188 wxChar chLast = '\0';
86948c99 189
dbcf443c
VZ
190 // the beginning of the current line, changes inside the loop
191 wxString::const_iterator lineStart = str.begin();
192 const wxString::const_iterator end = str.end();
193 for ( wxString::const_iterator p = lineStart; p != end; p++ )
194 {
195 const wxChar ch = *p;
196 switch ( ch )
197 {
198 case '\n':
199 // could be a DOS or Unix EOL
200 if ( chLast == '\r' )
201 {
82bf96f5
VS
202 if ( p - 1 >= lineStart )
203 {
204 AddLine(wxString(lineStart, p - 1), wxTextFileType_Dos);
205 }
206 else
207 {
208 // there were two line endings, so add an empty line:
209 AddLine(wxEmptyString, wxTextFileType_Dos);
210 }
dbcf443c
VZ
211 }
212 else // bare '\n', Unix style
213 {
214 AddLine(wxString(lineStart, p), wxTextFileType_Unix);
215 }
216
217 lineStart = p + 1;
218 break;
219
220 case '\r':
221 if ( chLast == '\r' )
222 {
223 // Mac empty line
224 AddLine(wxEmptyString, wxTextFileType_Mac);
86948c99 225 lineStart = p + 1;
dbcf443c
VZ
226 }
227 //else: we don't know what this is yet -- could be a Mac EOL or
228 // start of DOS EOL so wait for next char
229 break;
230
231 default:
232 if ( chLast == '\r' )
233 {
234 // Mac line termination
82bf96f5
VS
235 if ( p - 1 >= lineStart )
236 {
237 AddLine(wxString(lineStart, p - 1), wxTextFileType_Mac);
238 }
239 else
240 {
241 // there were two line endings, so add an empty line:
242 AddLine(wxEmptyString, wxTextFileType_Mac);
243 }
dbcf443c
VZ
244 lineStart = p;
245 }
d9ade1df 246 }
86948c99 247
dbcf443c 248 chLast = ch;
86948c99 249 }
d9ade1df
VS
250
251 // anything in the last line?
dbcf443c 252 if ( lineStart != end )
d9ade1df 253 {
dbcf443c
VZ
254 // add unterminated last line
255 AddLine(wxString(lineStart, end), wxTextFileType_None);
c801d85f 256 }
c801d85f 257
cb719f2e 258 return true;
c801d85f
KB
259}
260
f42d2aba 261
830f8f11 262bool wxTextFile::OnWrite(wxTextFileType typeNew, const wxMBConv& conv)
c801d85f 263{
68c97af3 264 wxFileName fn = m_strBufferName;
baed1077
JS
265
266 // We do NOT want wxPATH_NORM_CASE here, or the case will not
267 // be preserved.
68c97af3 268 if ( !fn.IsAbsolute() )
32a0d013
VS
269 fn.Normalize(wxPATH_NORM_ENV_VARS | wxPATH_NORM_DOTS | wxPATH_NORM_TILDE |
270 wxPATH_NORM_ABSOLUTE | wxPATH_NORM_LONG);
68c97af3 271
deab4540 272 wxTempFile fileTmp(fn.GetFullPath());
c801d85f 273
a3a584a7
VZ
274 if ( !fileTmp.IsOpened() ) {
275 wxLogError(_("can't write buffer '%s' to disk."), m_strBufferName.c_str());
cb719f2e 276 return false;
a3a584a7 277 }
c801d85f 278
a3a584a7
VZ
279 size_t nCount = GetLineCount();
280 for ( size_t n = 0; n < nCount; n++ ) {
281 fileTmp.Write(GetLine(n) +
282 GetEOL(typeNew == wxTextFileType_None ? GetLineType(n)
283 : typeNew),
284 conv);
285 }
c801d85f 286
a3a584a7
VZ
287 // replace the old file with this one
288 return fileTmp.Commit();
ba7f9a90 289}
6164d85e 290
a1b82138 291#endif // wxUSE_TEXTFILE