Download presentation
Presentation is loading. Please wait.
1
Files and Streams
2
wxFile and wxFFile wxFile may be used for low-level input/output
(opening/closing, reading/writing, seeking, and so on) reports errors via wxLog and closes the file automatically in the destructor. wxFFile uses buffered input/output create a wxFile object using the default constructor followed by Create or Open, or the constructor that takes a file name and open mode (wxFile::read, wxFile::write, or wxFile::read_write). A wxFile can be closed with Close, which is called automatically when the object is destroyed.
3
Read - get data from the object with Read, passing a void
Read - get data from the object with Read, passing a void* buffer and the number of bytes to read. (returns the actual number of bytes read, or wxInvalidOffset if there was an error). Write - to write a void* buffer or wxString to the file Flush if you need the data to be written to the file immediately. EOF - to test for the end of the file, use Eof, which will return true if the file pointer is at the end of the file. wxFFile’s Eof will return true only if an attempt has been made to read past the end of the file. Seek and SeekEnd seek to a position in the file, taking an offset specified as starting from the beginning or end of the file, respectively. Tell returns the current offset from the start of the file as a wxFileOffset Access - call the static Access function to determine whether a file can be opened in a given mode. Exists is another static function that tests the existence of the given file.
4
#include “wx/file.h” if (!wxFile::Exists(wxT(“data.dat”))) return false; wxFile file(wxT(“data.dat”)); if ( !file.IsOpened() ) // get the file size wxFileOffset nSize = file.Length(); if ( nSize == wxInvalidOffset ) // read the whole file into memory wxUint* data = new wxUint8[nSize]; if ( fileMsg.Read(data, (size_t) nSize) != nSize ) { delete[] data; } file.Close();
5
bool WriteTextCtrlContents(wxTextCtrl* textCtrl,
const wxString& filename) { wxFile file; if (!file.Open(filename, wxFile::write)) return false int nLines = textCtrl->GetNumberOfLines(); bool ok = true; for ( int nLine = 0; ok && nLine < nLines; nLine++ ) ok = file.Write(textCtrl->GetLineText(nLine) + wxTextFile::GetEOL()); } file.Close(); return ok;
6
wxTextFile wxTextFile provides a very straightforward way to read and write small files and process them line-by-line. Use Open to read a file into memory and split it into lines, and use Write to save it. You can use GetLine or the array operator to retrieve a specified line, Iterate through the file with GetFirstLine, GetNextLine, and GetPrevLine. Add lines to the file with AddLine or InsertLine, and remove lines by passing the line number to RemoveLine. You can clear the whole file with Clear.
7
#include “wx/textfile.h”
void FilePrepend(const wxString& filename, const wxString& text) { wxTextFile file; if (file.Open(filename)) size_t i; for (i = 0; i < file.GetLineCount(); i++) file[i] = text + file[i]; } file.Write(filename);
8
wxTempFile wxTempFile is derived from wxFile and uses a temporary file to write data, not writing to the actual file until Commit is called. When you write a user’s data, it’s a good idea to write to a temporary file because if an error occurs during the save operation (such as a power failure, program bug, or other cataclysm), this error will not corrupt the current file on disk.
9
wxDir wxDir supports enumeration of files as well as directories.
GetFirst passing a pointer to a string to receive the found file name. GetNext until there are no more matching files and the function returns false. The file specification can contain wildcards, such as “*” (match any number of characters) and “?” (match one character). For the flags argument, pass a bit-list of wxDIR_FILES (match files), wxDIR_DIRS (match directories), wxDIR_HIDDEN (match hidden files)
10
#include “wx/dir.h” wxDir dir(wxGetCwd()); if ( !dir.IsOpened() ) { // Deal with the error here - wxDir already logs an error message // explaining the exact reason of the failure return; } puts(“Enumerating object files in current directory:”); wxString filename; wxString filespec = wxT(“*.*”); int flags = wxDIR_FILES|wxDIR_DIRS; bool cont = dir.GetFirst(&filename, filespec, flags); while ( cont ) wxLogMessage(wxT(“%s\n”), filename.c_str()); cont = dir.GetNext(&filename);
11
Error Handling Note that if there is a problem when enumerating files—for example, if the directory does not exist—wxDir will generate a log message. To suppress this behavior, use the wxLogNull object to temporarily disable logging:
12
// Create scope for logNull
{ wxLogNull logNull; wxDir dir(badDir); if ( !dir.IsOpened() ) return; }
13
wxFileName wxFileName models the name of a file;
it can parse and reconstitute the components of a file name, and it also provides a variety of file operations, some of which are static functions.
14
#include “wx/filename.h” // Create a filename from a string
wxFileName fname(wxT(“MyFile.txt”)); // Normalize, including making sure the filename is in its long form on Windows fname.Normalize(wxPATH_NORM_LONG|wxPATH_NORM_DOTS| wxPATH_NORM_TILDE| wxPATH_NORM_ABSOLUTE); // Get the full path as a string wxString filename = fname.GetFullPath(); // Make it relative to the current path fname.MakeRelativeTo(wxFileName::GetCwd()); // Does the file exist? bool exists = fname.FileExists();
15
// Does a different file exist?
bool exists2 = wxFileName::FileExists(wxT(“c:\\temp.txt”)); // Return the name part wxString name = fname.GetName(); // Return the path part wxString path = fname.GetPath(); // Return the short version on Windows, or identity on other systems wxString shortForm = fname.GetShortPath(); // Makes a directory bool ok = wxFileName::Mkdir(wxT(“c:\\thing”));
16
File Functions wx/filefn.h.
See also the wxFileName class, especially the static functions you can use without constructing a wxFileName object, such as wxFileName::FileExists.
17
wxDirExists(dir) Tests whether the directory exists
wxDirExists(dir) Tests whether the directory exists. See also wxFileName::DirExists. wxConcatFiles(f1, f2, f3) Concatenates f1 and f2 to f3, returning true on success. wxCopyFile(f1, f2, overwrite) Copies f1 to f2, optionally overwriting f2. Returns true on success. wxFileExists(file) Tests whether the file exists. See also wxFileName::FileExists.
18
wxFileModificationTime(file) Returns the time (as a time_t) of the last file modification. See also wxFileName::GetModificationTime, which returns a wxDateTime. wxFileNameFromPath(file) Returns the file name part of the path. The recommended method is to use wxFileName::SplitPath. wxGetCwd() Returns the current working directory. See also wxFileName::GetCwd. wxGetDiskSpace Returns available disk space on the disk containing the given path, returning total space and freespace in the wxLongLong pointer arguments.
19
wxIsAbsolutePath(path) Tests whether the given path is absolute or relative.
wxMkdir(dir, permission=777) Creates the given directory, optionally specifying an access mask. The parent directory must exist. Returns true on success. wxPathOnly(path) Returns the directory part of the given path. wxRemoveFile(file) Removes the file, returning true on success. wxRenameFile(file1, file2) Renames the file, returning true on success. This may return false if the files are on different volumes, for example, in which case a file copy is required. wxRmdir(file) Removes the directory, returning true on success. wxSetWorkingDirectory(file) Sets the current working directory, returning true on success.
20
It’s also useful to know about the wxFILE_SEP_PATH symbol, which is the appropriate path separator for the platform on which the application is running (for example, backslash on Windows and forward slash on Unix-based systems).
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.