1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/textfile.cpp
3 // Purpose: implementation of wxTextFile class
4 // Author: Vadim Zeitlin
7 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 #include "wx/wxprec.h"
21 #if !wxUSE_FILE || !wxUSE_TEXTBUFFER
23 #define wxUSE_TEXTFILE 0
29 #include "wx/string.h"
35 #include "wx/textfile.h"
36 #include "wx/filename.h"
37 #include "wx/buffer.h"
39 // ============================================================================
40 // wxTextFile class implementation
41 // ============================================================================
43 wxTextFile::wxTextFile(const wxString
& strFileName
)
44 : wxTextBuffer(strFileName
)
49 // ----------------------------------------------------------------------------
51 // ----------------------------------------------------------------------------
53 bool wxTextFile::OnExists() const
55 return wxFile::Exists(m_strBufferName
);
59 bool wxTextFile::OnOpen(const wxString
&strBufferName
, wxTextBufferOpenMode OpenMode
)
61 wxFile::OpenMode FileOpenMode
;
66 wxFAIL_MSG( wxT("unknown open mode in wxTextFile::Open") );
70 FileOpenMode
= wxFile::read
;
74 FileOpenMode
= wxFile::write
;
78 return m_file
.Open(strBufferName
.c_str(), FileOpenMode
);
82 bool wxTextFile::OnClose()
84 return m_file
.Close();
88 bool wxTextFile::OnRead(const wxMBConv
& conv
)
90 // file should be opened
91 wxASSERT_MSG( m_file
.IsOpened(), wxT("can't read closed file") );
93 // read the entire file in memory: this is not the most efficient thing to
94 // do it but there is no good way to avoid it in Unicode build because if
95 // we read the file block by block we can't convert each block to Unicode
96 // separately (the last multibyte char in the block might be only partially
97 // read and so the conversion would fail) and, as the file contents is kept
98 // in memory by wxTextFile anyhow, it shouldn't be a big problem to read
102 // number of bytes to (try to) read from disk at once
103 static const size_t BLOCK_SIZE
= 4096;
107 // first determine if the file is seekable or not and so whether we can
108 // determine its length in advance
109 wxFileOffset fileLength
;
112 fileLength
= m_file
.Length();
115 // some non-seekable files under /proc under Linux pretend that they're
116 // seekable but always return 0; others do return an error
117 const bool seekable
= fileLength
!= wxInvalidOffset
&& fileLength
!= 0;
120 // we know the required length, so set the buffer size in advance
121 bufSize
= fileLength
;
122 if ( !buf
.extend(bufSize
) )
125 // if the file is seekable, also check that we're at its beginning
126 wxASSERT_MSG( m_file
.Tell() == 0, wxT("should be at start of file") );
128 char *dst
= buf
.data();
129 for ( size_t nRemaining
= bufSize
; nRemaining
> 0; )
131 size_t nToRead
= BLOCK_SIZE
;
133 // the file size could have changed, avoid overflowing the buffer
135 if ( nToRead
> nRemaining
)
136 nToRead
= nRemaining
;
138 ssize_t nRead
= m_file
.Read(dst
, nToRead
);
140 if ( nRead
== wxInvalidOffset
)
142 // read error (error message already given in wxFile::Read)
148 // this file can't be empty because we checked for this above
149 // so this must be the end of file
157 wxASSERT_MSG( dst
- buf
.data() == (wxFileOffset
)bufSize
,
158 wxT("logic error") );
160 else // file is not seekable
162 char block
[BLOCK_SIZE
];
165 ssize_t nRead
= m_file
.Read(block
, WXSIZEOF(block
));
167 if ( nRead
== wxInvalidOffset
)
169 // read error (error message already given in wxFile::Read)
175 // if no bytes have been read, presumably this is a
176 // valid-but-empty file
180 // otherwise we've finished reading the file
184 // extend the buffer for new data
185 if ( !buf
.extend(bufSize
+ nRead
) )
188 // and append it to the buffer
189 memcpy(buf
.data() + bufSize
, block
, nRead
);
194 const wxString
str(buf
, conv
, bufSize
);
196 // there's no risk of this happening in ANSI build
198 if ( bufSize
> 4 && str
.empty() )
200 wxLogError(_("Failed to convert file \"%s\" to Unicode."), GetName());
203 #endif // wxUSE_UNICODE
205 // we don't need this memory any more
209 // now break the buffer in lines
211 // last processed character, we need to know if it was a CR or not
212 wxChar chLast
= '\0';
214 // the beginning of the current line, changes inside the loop
215 wxString::const_iterator lineStart
= str
.begin();
216 const wxString::const_iterator end
= str
.end();
217 for ( wxString::const_iterator p
= lineStart
; p
!= end
; p
++ )
219 const wxChar ch
= *p
;
223 // could be a DOS or Unix EOL
224 if ( chLast
== '\r' )
226 if ( p
- 1 >= lineStart
)
228 AddLine(wxString(lineStart
, p
- 1), wxTextFileType_Dos
);
232 // there were two line endings, so add an empty line:
233 AddLine(wxEmptyString
, wxTextFileType_Dos
);
236 else // bare '\n', Unix style
238 AddLine(wxString(lineStart
, p
), wxTextFileType_Unix
);
245 if ( chLast
== '\r' )
248 AddLine(wxEmptyString
, wxTextFileType_Mac
);
251 //else: we don't know what this is yet -- could be a Mac EOL or
252 // start of DOS EOL so wait for next char
256 if ( chLast
== '\r' )
258 // Mac line termination
259 if ( p
- 1 >= lineStart
)
261 AddLine(wxString(lineStart
, p
- 1), wxTextFileType_Mac
);
265 // there were two line endings, so add an empty line:
266 AddLine(wxEmptyString
, wxTextFileType_Mac
);
275 // anything in the last line?
276 if ( lineStart
!= end
)
278 // add unterminated last line
279 AddLine(wxString(lineStart
, end
), wxTextFileType_None
);
286 bool wxTextFile::OnWrite(wxTextFileType typeNew
, const wxMBConv
& conv
)
288 wxFileName fn
= m_strBufferName
;
290 // We do NOT want wxPATH_NORM_CASE here, or the case will not
292 if ( !fn
.IsAbsolute() )
293 fn
.Normalize(wxPATH_NORM_ENV_VARS
| wxPATH_NORM_DOTS
| wxPATH_NORM_TILDE
|
294 wxPATH_NORM_ABSOLUTE
| wxPATH_NORM_LONG
);
296 wxTempFile
fileTmp(fn
.GetFullPath());
298 if ( !fileTmp
.IsOpened() ) {
299 wxLogError(_("can't write buffer '%s' to disk."), m_strBufferName
.c_str());
303 size_t nCount
= GetLineCount();
304 for ( size_t n
= 0; n
< nCount
; n
++ ) {
305 fileTmp
.Write(GetLine(n
) +
306 GetEOL(typeNew
== wxTextFileType_None
? GetLineType(n
)
311 // replace the old file with this one
312 return fileTmp
.Commit();
315 #endif // wxUSE_TEXTFILE