📄 qdir.cpp
字号:
/************************************************************************ Copyright (C) 2000-2005 Trolltech AS. All rights reserved.**** This file is part of the Qtopia Environment.** ** This program is free software; you can redistribute it and/or modify it** under the terms of the GNU General Public License as published by the** Free Software Foundation; either version 2 of the License, or (at your** option) any later version.** ** A copy of the GNU GPL license version 2 is included in this package as ** LICENSE.GPL.**** This program is distributed in the hope that it will be useful, but** WITHOUT ANY WARRANTY; without even the implied warranty of** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ** See the GNU General Public License for more details.**** In addition, as a special exception Trolltech gives permission to link** the code of this program with Qtopia applications copyrighted, developed** and distributed by Trolltech under the terms of the Qtopia Personal Use** License Agreement. You must comply with the GNU General Public License** in all respects for all of the code used other than the applications** licensed under the Qtopia Personal Use License Agreement. If you modify** this file, you may extend this exception to your version of the file,** but you are not obligated to do so. If you do not wish to do so, delete** this exception statement from your version.** ** See http://www.trolltech.com/gpl/ for GPL licensing information.**** Contact info@trolltech.com if any conditions of this licensing are** not clear to you.************************************************************************/#include "qplatformdefs.h"#include "qdir.h"#ifndef QT_NO_DIR#include <private/qdir_p.h>#include "qfileinfo.h"#include "qregexp.h"#include "qstringlist.h"#include "qdeepcopy.h"#include <limits.h>#if defined(Q_FS_FAT) && !defined(Q_OS_UNIX)const bool CaseSensitiveFS = FALSE;#elseconst bool CaseSensitiveFS = TRUE;#endif/*! \class QDir \reentrant \brief The QDir class provides access to directory structures and their contents in a platform-independent way. \ingroup io \mainclass A QDir is used to manipulate path names, access information regarding paths and files, and manipulate the underlying file system. A QDir can point to a file using either a relative or an absolute path. Absolute paths begin with the directory separator "/" (optionally preceded by a drive specification under Windows). If you always use "/" as a directory separator, Qt will translate your paths to conform to the underlying operating system. Relative file names begin with a directory name or a file name and specify a path relative to the current directory. The "current" path refers to the application's working directory. A QDir's own path is set and retrieved with setPath() and path(). An example of an absolute path is the string "/tmp/quartz", a relative path might look like "src/fatlib". You can use the function isRelative() to check if a QDir is using a relative or an absolute file path. Call convertToAbs() to convert a relative QDir to an absolute one. For a simplified path use cleanDirPath(). To obtain a path which has no symbolic links or redundant ".." elements use canonicalPath(). The path can be set with setPath(), and changed with cd() and cdUp(). QDir provides several static functions, for example, setCurrent() to set the application's working directory and currentDirPath() to retrieve the application's working directory. Access to some common paths is provided with the static functions, current(), home() and root() which return QDir objects or currentDirPath(), homeDirPath() and rootDirPath() which return the path as a string. If you want to know about your application's path use \l{QApplication::applicationDirPath()}. The number of entries in a directory is returned by count(). Obtain a string list of the names of all the files and directories in a directory with entryList(). If you prefer a list of QFileInfo pointers use entryInfoList(). Both these functions can apply a name filter, an attributes filter (e.g. read-only, files not directories, etc.), and a sort order. The filters and sort may be set with calls to setNameFilter(), setFilter() and setSorting(). They may also be specified in the entryList() and entryInfoList()'s arguments. Create a new directory with mkdir(), rename a directory with rename() and remove an existing directory with rmdir(). Remove a file with remove(). You can interrogate a directory with exists(), isReadable() and isRoot(). To get a path with a filename use filePath(), and to get a directory name use dirName(); neither of these functions checks for the existence of the file or directory. The list of root directories is provided by drives(); on Unix systems this returns a list containing one root directory, "/"; on Windows the list will usually contain "C:/", and possibly "D:/", etc. If you need the path in a form suitable for the underlying operating system use convertSeparators(). Examples: See if a directory exists. \code QDir d( "example" ); // "./example" if ( !d.exists() ) qWarning( "Cannot find the example directory" ); \endcode Traversing directories and reading a file. \code QDir d = QDir::root(); // "/" if ( !d.cd("tmp") ) { // "/tmp" qWarning( "Cannot find the \"/tmp\" directory" ); } else { QFile f( d.filePath("ex1.txt") ); // "/tmp/ex1.txt" if ( !f.open(IO_ReadWrite) ) qWarning( "Cannot create the file %s", f.name() ); } \endcode A program that lists all the files in the current directory (excluding symbolic links), sorted by size, smallest first: \code #include <stdio.h> #include <qdir.h> int main( int argc, char **argv ) { QDir d; d.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks ); d.setSorting( QDir::Size | QDir::Reversed ); const QFileInfoList *list = d.entryInfoList(); QFileInfoListIterator it( *list ); QFileInfo *fi; printf( " Bytes Filename\n" ); while ( (fi = it.current()) != 0 ) { printf( "%10li %s\n", fi->size(), fi->fileName().latin1() ); ++it; } return 0; } \endcode \sa QApplication::applicationDirPath()*//*! Constructs a QDir pointing to the current directory. \sa currentDirPath()*/QDir::QDir(){ dPath = QString::fromLatin1("."); init();}/*! Constructs a QDir with path \a path, that filters its entries by name using \a nameFilter and by attributes using \a filterSpec. It also sorts the names using \a sortSpec. The default \a nameFilter is an empty string, which excludes nothing; the default \a filterSpec is \c All, which also means exclude nothing. The default \a sortSpec is \c Name|IgnoreCase, i.e. sort by name case-insensitively. Example that lists all the files in "/tmp": \code QDir d( "/tmp" ); for ( int i = 0; i < d.count(); i++ ) printf( "%s\n", d[i] ); \endcode If \a path is "" or QString::null, QDir uses "." (the current directory). If \a nameFilter is "" or QString::null, QDir uses the name filter "*" (all files). Note that \a path need not exist. \sa exists(), setPath(), setNameFilter(), setFilter(), setSorting()*/QDir::QDir( const QString &path, const QString &nameFilter, int sortSpec, int filterSpec ){ init(); dPath = cleanDirPath( path ); if ( dPath.isEmpty() ) dPath = QString::fromLatin1("."); nameFilt = nameFilter; if ( nameFilt.isEmpty() ) nameFilt = QString::fromLatin1("*"); filtS = (FilterSpec)filterSpec; sortS = (SortSpec)sortSpec;}/*! Constructs a QDir that is a copy of the directory \a d. \sa operator=()*/QDir::QDir( const QDir &d ){ dPath = d.dPath; fList = 0; fiList = 0; nameFilt = d.nameFilt; dirty = TRUE; allDirs = d.allDirs; filtS = d.filtS; sortS = d.sortS;}/*! Refreshes the directory information.*/void QDir::refresh() const{ QDir* that = (QDir*) this; that->dirty = TRUE;}void QDir::init(){ fList = 0; fiList = 0; nameFilt = QString::fromLatin1("*"); dirty = TRUE; allDirs = FALSE; filtS = All; sortS = SortSpec(Name | IgnoreCase);}/*! Destroys the QDir frees up its resources.*/QDir::~QDir(){ delete fList; delete fiList;}/*! Sets the path of the directory to \a path. The path is cleaned of redundant ".", ".." and of multiple separators. No check is made to ensure that a directory with this path exists. The path can be either absolute or relative. Absolute paths begin with the directory separator "/" (optionally preceded by a drive specification under Windows). Relative file names begin with a directory name or a file name and specify a path relative to the current directory. An example of an absolute path is the string "/tmp/quartz", a relative path might look like "src/fatlib". \sa path(), absPath(), exists(), cleanDirPath(), dirName(), absFilePath(), isRelative(), convertToAbs()*/void QDir::setPath( const QString &path ){ dPath = cleanDirPath( path ); if ( dPath.isEmpty() ) dPath = QString::fromLatin1("."); dirty = TRUE;}/*! \fn QString QDir::path() const Returns the path, this may contain symbolic links, but never contains redundant ".", ".." or multiple separators. The returned path can be either absolute or relative (see setPath()). \sa setPath(), absPath(), exists(), cleanDirPath(), dirName(), absFilePath(), convertSeparators()*//*! Returns the absolute path (a path that starts with "/" or with a drive specification), which may contain symbolic links, but never contains redundant ".", ".." or multiple separators. \sa setPath(), canonicalPath(), exists(), cleanDirPath(), dirName(), absFilePath()*/QString QDir::absPath() const{ if ( QDir::isRelativePath(dPath) ) { QString tmp = currentDirPath(); if ( tmp.right(1) != QString::fromLatin1("/") ) tmp += '/'; tmp += dPath; return cleanDirPath( tmp ); } else { return cleanDirPath( dPath ); }}/*! Returns the name of the directory; this is \e not the same as the path, e.g. a directory with the name "mail", might have the path "/var/spool/mail". If the directory has no name (e.g. it is the root directory) QString::null is returned. No check is made to ensure that a directory with this name actually exists. \sa path(), absPath(), absFilePath(), exists(), QString::isNull()*/QString QDir::dirName() const{ int pos = dPath.findRev( '/' ); if ( pos == -1 ) return dPath; return dPath.right( dPath.length() - pos - 1 );}/*! Returns the path name of a file in the directory. Does \e not check if the file actually exists in the directory. If the QDir is relative the returned path name will also be relative. Redundant multiple separators or "." and ".." directories in \a fileName will not be removed (see cleanDirPath()). If \a acceptAbsPath is TRUE a \a fileName starting with a separator "/" will be returned without change. If \a acceptAbsPath is FALSE an absolute path will be prepended to the fileName and the resultant string returned. \sa absFilePath(), isRelative(), canonicalPath()*/QString QDir::filePath( const QString &fileName, bool acceptAbsPath ) const{ if ( acceptAbsPath && !isRelativePath(fileName) ) return QString(fileName); QString tmp = dPath; if ( tmp.isEmpty() || (tmp[(int)tmp.length()-1] != '/' && !!fileName && fileName[0] != '/') ) tmp += '/'; tmp += fileName; return tmp;}/*! Returns the absolute path name of a file in the directory. Does \e not check if the file actually exists in the directory. Redundant multiple separators or "." and ".." directories in \a fileName will not be removed (see cleanDirPath()). If \a acceptAbsPath is TRUE a \a fileName starting with a separator "/" will be returned without change. If \a acceptAbsPath is FALSE an absolute path will be prepended to the fileName and the resultant string returned. \sa filePath()*/QString QDir::absFilePath( const QString &fileName, bool acceptAbsPath ) const{ if ( acceptAbsPath && !isRelativePath( fileName ) ) return fileName; QString tmp = absPath();#ifdef Q_OS_WIN32 if ( fileName[0].isLetter() && fileName[1] == ':' ) { int drv = fileName.upper()[0].latin1() - 'A' + 1; if ( _getdrive() != drv ) { QT_WA( { TCHAR buf[PATH_MAX]; ::_wgetdcwd( drv, buf, PATH_MAX ); tmp.setUnicodeCodes( (ushort*)buf, ::wcslen(buf) ); }, { char buf[PATH_MAX]; ::_getdcwd( drv, buf, PATH_MAX ); tmp = buf; } ); if ( !tmp.endsWith("\\") ) tmp += "\\"; tmp += fileName.right( fileName.length() - 2 ); int x; for ( x = 0; x < (int) tmp.length(); x++ ) { if ( tmp[x] == '\\' ) tmp[x] = '/'; } } } else#endif { if ( tmp.isEmpty() || (tmp[(int)tmp.length()-1] != '/' && !!fileName && fileName[0] != '/') ) tmp += '/'; tmp += fileName; } return tmp;}/*! Returns \a pathName with the '/' separators converted to separators that are appropriate for the underlying operating system. On Windows, convertSeparators("c:/winnt/system32") returns "c:\winnt\system32". The returned string may be the same as the argument on some operating systems, for example on Unix.*/QString QDir::convertSeparators( const QString &pathName ){ QString n( pathName );#if defined(Q_FS_FAT) || defined(Q_OS_OS2EMX) for ( int i=0; i<(int)n.length(); i++ ) { if ( n[i] == '/' ) n[i] = '\\'; }#elif defined(Q_OS_MAC9) while(n.length() && n[0] == '/' ) n = n.right(n.length()-1); for ( int i=0; i<(int)n.length(); i++ ) { if ( n[i] == '/' ) n[i] = ':';
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -