Как удалить файл в qt
Редко встречается приложение, которое не обращается к файлам. Работа с директориями (папками, в терминологии ОС Windows) и файлами — это та область, в которой не все операции являются платформонезависимыми, поэтому Qt предоставляет свою собственную поддержку этих операций, состоящую из следующих классов:
- QDir — для работы с директориями;
- QFile — для работы с файлами;
- QFileInfо — для получения файловой информации;
- QIODevice — абстрактный класс для ввода/вывода;
- QBuffer — для эмуляции файлов в памяти компьютера.
Ввод/вывод. Класс QIODevice
QIODevice — это абстрактный класс, обобщающий устройство ввода/вывода, который содержит виртуальные методы для открытия и закрытия устройства ввода/вывода, а также для чтения и записи блоков данных или отдельных символов.
Реализация конкретного устройства происходит в унаследованных классах.
В Qt есть четыре класса, наследующие класс QIODevice:
- QFile — класс для проведения операций с файлами;
- QBuffer — позволяет записывать и считывать данные в массив QByteArray, как будто бы это устройство или файл;
- QAbstractSocket — базовый класс для сетевой коммуникации посредством сокетов.
- QProcess — этот класс предоставляет возможность запуска процессов с дополнительными аргументами и позволяет обмениваться информацией с этими процессами посредством методов, определенных в QIODevice.
Для работы с устройством его необходимо открыть в одном из режимов, определенных В заголовочном файле класса QIODevice:
- QIODevice::NotOpen — устройство не открыто (это значение не имеет смысла передавать в метод open() );
- QIODevice::ReadOnly — открытие устройства только для чтения данных;
- QIODevice::writeOnly — открытие устройства только для записи данных;
- QIODevice::ReadWrite — открытие устройства для чтения и записи данных (то же, что и IO_ReadOnly | IO_WriteOnly );
- QIODevice::Append — открытие устройства для добавления данных;
- QIODevice::Unbuffered — открытие для непосредственного доступа к данным, в обход промежуточных буферов чтения и записи;
- QIODevice::Text — применяются преобразования символов переноса строки в зависимости от платформы. Для ОС Windows, например — \r\n, а для MacOS X и UNIX — /r;
- QIODevice::Truncate — все данные устройства, по возможности, должны быть удалены при открытии.
Для того чтобы в любой момент времени исполнения программы узнать, в каком из режимов было открыто устройство, нужно вызвать метод openMode() .
Считывать и записывать данные можно с помощью методов read() и write() соответственно. Для чтения всех данных сразу определен метод readAll() , который возвращает их в объекте типа QByteArray. Строку или символ можно прочитать методами readLine() и getChar() соответственно.
В классе QIODevice определен метод для смены текущего положения seek() . Получить текущее положение можно вызовом метода pos() . Но не забывайте, что эти методы применимы только для прямого доступа к данным. При последовательном доступе, каким является сетевое соединение, они теряют смысл. Более того, в этом случае теряет смысл и метод size() , возвращающий размер данных устройства. Все эти операции применимы только для QFile, QBuffer и QTemporaryFile.
Для создания собственного класса устройства ввода/вывода, для которого Qt не предоставляет поддержки, необходимо унаследовать класс QIODevice и реализовать в нем методы readData() и writeData() . В большинстве случаев может потребоваться перезаписать методы open() , close() и atEnd() .
Благодаря интерфейсу класса QIODevice можно работать со всеми устройствами одинаково, при этом не имеет значения, является ли устройство файлом, буфером или другим устройством. Выведем на консоль данные из любого устройства.
Класс QIODevice предоставляет ряд методов, с помощью которых можно получить информацию об устройстве ввода/вывода. Например, одни устройства могут только записывать информацию, другие — только считывать, а третьи способны делать и то, и другое. Чтобы узнать об этом, следует воспользоваться методами isReadable() и isWriteable() .
Почему не получается удалить file? Как удалить файл?
почему не получается удалить file? public void onClick(View v) < .
Удалить все лишние пробелы. Удалить из него первое слово. Дописать в тот же файл измененую строку
я создал текстовый файл теперь нужно удалить все лишние пробелы. Удалить из него первое слово.
Удалить файл и удалить информацию о нём
Доброго времени суток. В общем есть такая вот функция, которая выводит файлы, их можно скачать и.
Куда спрятать файл от пользователя, или как запретить удалить файл
Всем доброго времени суток. Кто может подсказать куда можно заныкать файл чтобы его не мог найти.
Если Qt'шный проект запускается прямо из QtCreatora, то там по умолчанию текущая директория не та, где лежат исходники и не та, где находится exe'шник. Попробуйте использовать полный путь к файлу.
Так же возможно, что файл в этот момент открыт, поэтому не может быть удалён.
Humanoid, Файл не используется и лежит там где нужно, это 100%. Полный путь указать пробовал - аналогично.
Можно только гадать! кирилица, пути, глобальные переменные и т.п.
Попробуйте изменить название на енглийское, попробуйте изменить
пути (опять же вопрос линукс или винда?), запускате файл вручную.
По названию и вопрос: а зачем вам это? (может "ресурсами обойтись")
Как 100% удалить используемый сторонним приложением файл?
Есть простой способ проверить правильность написания пути.
Вызвать метод QFile::exists(const QString &fileName), чтобы определить существование файла с таким именем по такому пути.
alexey_rage, я через openFileName указываю файл, мне кажется там тоже верно))
я пробовал и в корень диска файл кидать, указывал полный путь и пробовал удалить - ничего. Может нужно либку какую подключить или ещё чего?
Пробовал Windows.h подключать. вообще не компилируется, показывает ошибку в либке.
Добавлено через 17 минут
alexey_rage, хотя я попробовал сделать так, как вы написали.
Не работает, хоть файл там есть.
Добавлено через 8 минут
_SASA_, винда. Попробовал всё на латинице - не помогло.
Добавлено через 3 минуты
а вот кажется и проблема.
пишет вот такое: "предупреждение: C4129: 'l' : unrecognized character escape sequence"
на вот это
Note: All functions in this class are reentrant.
Public Types
Public Functions
QFile(const QString &name, QObject *parent) | |
QFile(QObject *parent) | |
QFile(const QString &name) | |
QFile() | |
virtual | ~QFile() |
bool | copy(const QString &newName) |
bool | exists() const |
bool | link(const QString &linkName) |
bool | moveToTrash() |
bool | open(FILE *fh, QIODevice::OpenMode mode, QFileDevice::FileHandleFlags handleFlags = DontCloseHandle) |
bool | open(int fd, QIODevice::OpenMode mode, QFileDevice::FileHandleFlags handleFlags = DontCloseHandle) |
bool | remove() |
bool | rename(const QString &newName) |
void | setFileName(const QString &name) |
QString | symLinkTarget() const |
Reimplemented Public Functions
virtual QString | fileName() const override |
virtual bool | open(QIODevice::OpenMode mode) override |
virtual QFileDevice::Permissions | permissions() const override |
virtual bool | resize(qint64 sz) override |
virtual bool | setPermissions(QFileDevice::Permissions permissions) override |
virtual qint64 | size() const override |
Static Public Members
bool | copy(const QString &fileName, const QString &newName) |
QString | decodeName(const QByteArray &localFileName) |
QString | decodeName(const char *localFileName) |
QByteArray | encodeName(const QString &fileName) |
bool | exists(const QString &fileName) |
bool | link(const QString &fileName, const QString &linkName) |
bool | moveToTrash(const QString &fileName, QString *pathInTrash = nullptr) |
QFileDevice::Permissions | permissions(const QString &fileName) |
bool | remove(const QString &fileName) |
bool | rename(const QString &oldName, const QString &newName) |
bool | resize(const QString &fileName, qint64 sz) |
bool | setPermissions(const QString &fileName, QFileDevice::Permissions permissions) |
QString | symLinkTarget(const QString &fileName) |
Detailed Description
QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream.
The file name is usually passed in the constructor, but it can be set at any time using setFileName(). QFile expects the file separator to be '/' regardless of operating system. The use of other separators (e.g., '\') is not supported.
You can check for a file's existence using exists(), and remove a file using remove(). (More advanced file system related operations are provided by QFileInfo and QDir.)
The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.
The size of the file is returned by size(). You can get the current file position using pos(), or move to a new file position using seek(). If you've reached the end of the file, atEnd() returns true .
Reading Files Directly
The following example reads a text file line by line:
The QIODevice::Text flag passed to open() tells Qt to convert Windows-style line terminators ("\r\n") into C++-style terminators ("\n"). By default, QFile assumes binary, i.e. it doesn't perform any conversion on the bytes stored in the file.
Using Streams to Read Files
The next example uses QTextStream to read a text file line by line:
QDataStream is similar, in that you can use operator>() to read it back. See the class documentation for details.
On Unix, there are some special system files (e.g. in /proc ) for which size() will always return 0, yet you may still be able to read more data from such a file; the data is generated in direct response to you calling read(). In this case, however, you cannot use atEnd() to determine if there is more data to read (since atEnd() will return true for a file that claims to have size 0). Instead, you should either call readAll(), or call read() or readLine() repeatedly until no more data can be read. The next example uses QTextStream to read /proc/modules line by line:
Signals
Unlike other QIODevice implementations, such as QTcpSocket, QFile does not emit the aboutToClose(), bytesWritten(), or readyRead() signals. This implementation detail means that QFile is not suitable for reading and writing certain types of files, such as device files on Unix platforms.
Platform Specific Issues
File permissions are handled differently on Unix-like systems and Windows. In a non writable directory on Unix-like systems, files cannot be created. This is not always the case on Windows, where, for instance, the 'My Documents' directory usually is not writable, but it is still possible to create files in it.
Qt's understanding of file permissions is limited, which affects especially the QFile::setPermissions() function. On Windows, Qt will set only the legacy read-only flag, and that only when none of the Write* flags are passed. Qt does not manipulate access control lists (ACLs), which makes this function mostly useless for NTFS volumes. It may still be of use for USB sticks that use VFAT file systems. POSIX ACLs are not manipulated, either.
Member Type Documentation
typedef QFile:: DecoderFn
This class provides access to the local filesystem, providing functions for renaming and removing files and directories, and for creating new directories. In the simplest case, it can be used with a suitable display widget as part of a browser or filter.
QFileSystemModel can be accessed using the standard interface provided by QAbstractItemModel, but it also provides some convenience functions that are specific to a directory model. The fileInfo(), isDir(), fileName() and filePath() functions provide information about the underlying files and directories related to items in the model. Directories can be created and removed using mkdir(), rmdir().
Note: QFileSystemModel requires an instance of QApplication.
Example Usage
A directory model that displays the contents of a default directory is usually constructed with a parent object:
A tree view can be used to display the contents of the model
and the contents of a particular directory can be displayed by setting the tree view's root index:
The view's root index can be used to control how much of a hierarchical model is displayed. QFileSystemModel provides a convenience function that returns a suitable model index for a path to a directory within the model.
Caching and Performance
QFileSystemModel will not fetch any files or directories until setRootPath() is called. This will prevent any unnecessary querying on the file system until that point such as listing the drives on Windows.
Unlike QDirModel, QFileSystemModel uses a separate thread to populate itself so it will not cause the main thread to hang as the file system is being queried. Calls to rowCount() will return 0 until the model populates a directory.
QFileSystemModel keeps a cache with file information. The cache is automatically kept up to date using the QFileSystemWatcher.
Member Type Documentation
enum QFileSystemModel:: Option
flags QFileSystemModel:: Options
Constant | Value | Description |
---|---|---|
QFileSystemModel::DontWatchForChanges | 0x00000001 | Do not add file watchers to the paths. This reduces overhead when using the model for simple tasks like line edit completion. |
QFileSystemModel::DontResolveSymlinks | 0x00000002 | Don't resolve symlinks in the file system model. By default, symlinks are resolved. |
QFileSystemModel::DontUseCustomDirectoryIcons | 0x00000004 | Always use the default directory icon. Some platforms allow the user to set a different icon. Custom icon lookup causes a big performance impact over network or removable drives. This sets the QFileIconProvider::DontUseCustomDirectoryIcons option in the icon provider accordingly. |
This enum was introduced or modified in Qt 5.14.
The Options type is a typedef for QFlags. It stores an OR combination of Option values.
enum QFileSystemModel:: Roles
Constant | Value |
---|---|
QFileSystemModel::FileIconRole | Qt::DecorationRole |
QFileSystemModel::FilePathRole | Qt::UserRole + 1 |
QFileSystemModel::FileNameRole | Qt::UserRole + 2 |
QFileSystemModel::FilePermissions | Qt::UserRole + 3 |
Property Documentation
nameFilterDisables : bool
This property holds whether files that don't pass the name filter are hidden or disabled
This property is true by default
Access functions:
bool | nameFilterDisables () const |
void | setNameFilterDisables (bool enable) |
options : Options
This property holds the various options that affect the model
By default, all options are disabled.
Options should be set before changing properties.
This property was introduced in Qt 5.14.
Access functions:
QFileSystemModel::Options | options () const |
void | setOptions (QFileSystemModel::Options options) |
readOnly : bool
This property holds whether the directory model allows writing to the file system
If this property is set to false, the directory model will allow renaming, copying and deleting of files and directories.
This property is true by default
Access functions:
bool | isReadOnly () const |
void | setReadOnly (bool enable) |
resolveSymlinks : bool
This property holds whether the directory model should resolve symbolic links
This is only relevant on Windows.
By default, this property is true .
Access functions:
bool | resolveSymlinks () const |
void | setResolveSymlinks (bool enable) |
Member Function Documentation
QFileSystemModel:: QFileSystemModel ( QObject *parent = nullptr)
Constructs a file system model with the given parent.
[signal] void QFileSystemModel:: directoryLoaded (const QString &path)
This signal is emitted when the gatherer thread has finished to load the path.
This function was introduced in Qt 4.7.
[signal] void QFileSystemModel:: fileRenamed (const QString &path, const QString &oldName, const QString &newName)
This signal is emitted whenever a file with the oldName is successfully renamed to newName. The file is located in in the directory path.
[signal] void QFileSystemModel:: rootPathChanged (const QString &newPath)
This signal is emitted whenever the root path has been changed to a newPath.
[virtual] QFileSystemModel:: ~QFileSystemModel ()
Destroys this file system model.
[override virtual] bool QFileSystemModel:: canFetchMore (const QModelIndex &parent) const
Reimplements: QAbstractItemModel::canFetchMore(const QModelIndex &parent) const.
[override virtual] int QFileSystemModel:: columnCount (const QModelIndex &parent = QModelIndex()) const
Reimplements: QAbstractItemModel::columnCount(const QModelIndex &parent) const.
[override virtual] QVariant QFileSystemModel:: data (const QModelIndex &index, int role = Qt::DisplayRole) const
Reimplements: QAbstractItemModel::data(const QModelIndex &index, int role) const.
[override virtual] bool QFileSystemModel:: dropMimeData (const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
Reimplements: QAbstractItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent).
Handles the data supplied by a drag and drop operation that ended with the given action over the row in the model specified by the row and column and by the parent index. Returns true if the operation was successful.
[override virtual protected] bool QFileSystemModel:: event ( QEvent *event)
[override virtual] void QFileSystemModel:: fetchMore (const QModelIndex &parent)
QIcon QFileSystemModel:: fileIcon (const QModelIndex &index) const
Returns the icon for the item stored in the model under the given index.
QFileInfo QFileSystemModel:: fileInfo (const QModelIndex &index) const
Returns the QFileInfo for the item stored in the model under the given index.
QString QFileSystemModel:: fileName (const QModelIndex &index) const
Returns the file name for the item stored in the model under the given index.
QString QFileSystemModel:: filePath (const QModelIndex &index) const
Returns the path of the item stored in the model under the index given.
QDir::Filters QFileSystemModel:: filter () const
Returns the filter specified for the directory model.
If a filter has not been set, the default filter is QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs.
[override virtual] Qt::ItemFlags QFileSystemModel:: flags (const QModelIndex &index) const
Reimplements: QAbstractItemModel::flags(const QModelIndex &index) const.
[override virtual] bool QFileSystemModel:: hasChildren (const QModelIndex &parent = QModelIndex()) const
Reimplements: QAbstractItemModel::hasChildren(const QModelIndex &parent) const.
[override virtual] QVariant QFileSystemModel:: headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
Reimplements: QAbstractItemModel::headerData(int section, Qt::Orientation orientation, int role) const.
QFileIconProvider *QFileSystemModel:: iconProvider () const
Returns the file icon provider for this directory model.
[override virtual] QModelIndex QFileSystemModel:: index ( int row, int column, const QModelIndex &parent = QModelIndex()) const
Reimplements: QAbstractItemModel::index(int row, int column, const QModelIndex &parent) const.
QModelIndex QFileSystemModel:: index (const QString &path, int column = 0) const
This is an overloaded function.
Returns the model item index for the given path and column.
bool QFileSystemModel:: isDir (const QModelIndex &index) const
Returns true if the model item index represents a directory; otherwise returns false .
QDateTime QFileSystemModel:: lastModified (const QModelIndex &index) const
Returns the date and time when index was last modified.
[override virtual] QMimeData *QFileSystemModel:: mimeData (const QModelIndexList &indexes) const
Reimplements: QAbstractItemModel::mimeData(const QModelIndexList &indexes) const.
Returns an object that contains a serialized description of the specified indexes. The format used to describe the items corresponding to the indexes is obtained from the mimeTypes() function.
If the list of indexes is empty, nullptr is returned rather than a serialized empty list.
[override virtual] QStringList QFileSystemModel:: mimeTypes () const
Returns a list of MIME types that can be used to describe a list of items in the model.
QModelIndex QFileSystemModel:: mkdir (const QModelIndex &parent, const QString &name)
Create a directory with the name in the parent model index.
QVariant QFileSystemModel:: myComputer ( int role = Qt::DisplayRole) const
Returns the data stored under the given role for the item "My Computer".
QStringList QFileSystemModel:: nameFilters () const
Returns a list of filters applied to the names in the model.
[override virtual] QModelIndex QFileSystemModel:: parent (const QModelIndex &index) const
Reimplements: QAbstractItemModel::parent(const QModelIndex &index) const.
QFile::Permissions QFileSystemModel:: permissions (const QModelIndex &index) const
Returns the complete OR-ed together combination of QFile::Permission for the index.
bool QFileSystemModel:: remove (const QModelIndex &index)
Removes the model item index from the file system model and deletes the corresponding file from the file system, returning true if successful. If the item cannot be removed, false is returned.
Warning: This function deletes files from the file system; it does not move them to a location where they can be recovered.
bool QFileSystemModel:: rmdir (const QModelIndex &index)
Removes the directory corresponding to the model item index in the file system model and deletes the corresponding directory from the file system, returning true if successful. If the directory cannot be removed, false is returned.
Warning: This function deletes directories from the file system; it does not move them to a location where they can be recovered.
QDir QFileSystemModel:: rootDirectory () const
The currently set directory
QString QFileSystemModel:: rootPath () const
The currently set root path
[override virtual] int QFileSystemModel:: rowCount (const QModelIndex &parent = QModelIndex()) const
Reimplements: QAbstractItemModel::rowCount(const QModelIndex &parent) const.
[override virtual] bool QFileSystemModel:: setData (const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole)
Reimplements: QAbstractItemModel::setData(const QModelIndex &index, const QVariant &value, int role).
void QFileSystemModel:: setFilter ( QDir::Filters filters)
Sets the directory model's filter to that specified by filters.
Note that the filter you set should always include the QDir::AllDirs enum value, otherwise QFileSystemModel won't be able to read the directory structure.
void QFileSystemModel:: setIconProvider ( QFileIconProvider *provider)
Sets the provider of file icons for the directory model.
void QFileSystemModel:: setNameFilters (const QStringList &filters)
Sets the name filters to apply against the existing files.
void QFileSystemModel:: setOption ( QFileSystemModel::Option option, bool on = true)
Sets the given option to be enabled if on is true; otherwise, clears the given option.
Options should be set before changing properties.
This function was introduced in Qt 5.14.
QModelIndex QFileSystemModel:: setRootPath (const QString &newPath)
Sets the directory that is being watched by the model to newPath by installing a file system watcher on it. Any changes to files and directories within this directory will be reflected in the model.
If the path is changed, the rootPathChanged() signal will be emitted.
Note: This function does not change the structure of the model or modify the data available to views. In other words, the "root" of the model is not changed to include only files and directories within the directory specified by newPath in the file system.
[override virtual] QModelIndex QFileSystemModel:: sibling ( int row, int column, const QModelIndex &idx) const
Reimplements: QAbstractItemModel::sibling(int row, int column, const QModelIndex &index) const.
qint64 QFileSystemModel:: size (const QModelIndex &index) const
Returns the size in bytes of index. If the file does not exist, 0 is returned.
[override virtual] void QFileSystemModel:: sort ( int column, Qt::SortOrder order = Qt::AscendingOrder)
Reimplements: QAbstractItemModel::sort(int column, Qt::SortOrder order).
[override virtual] Qt::DropActions QFileSystemModel:: supportedDropActions () const
bool QFileSystemModel:: testOption ( QFileSystemModel::Option option) const
Returns true if the given option is enabled; otherwise, returns false.
This function was introduced in Qt 5.14.
[override virtual protected] void QFileSystemModel:: timerEvent ( QTimerEvent *event)
Reimplements: QObject::timerEvent(QTimerEvent *event).
QString QFileSystemModel:: type (const QModelIndex &index) const
Returns the type of file index such as "Directory" or "JPEG file".
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.
Класс QFile унаследован от класса QIODevice. В нем содержатся методы для работы с файлами: открытия, закрытия, чтения и записи данных. Создать объект можно, передав в конструкторе строку, содержащую имя файла. Можно ничего не передавать в конструкторе, а сделать это после создания объекта, вызовом метода setName() . Например:
В процессе работы с файлами иногда требуется узнать, открыт файл или нет. Для этого вызывается метод QIODevice::isOpen() , который вернет true , в том случае, если файл открыт, иначе — false . Чтобы закрыть файл, нужно вызвать метод close() . С закрытием произведется запись всех данных буфера. Если требуется произвести запись данных буфера в файл без его закрытия, то вызывается метод QFile::flush() .
Проверить, существует ли нужный вам файл, можно статическим методом QFile::exists() . Этот метод принимает строку, содержащую полный или относительный путь к файлу. Если файл найден, то метод возвратит true , в противном случае — false . Для проведения этой операции существует и нестатический метод QFile::exists() . Методы QIODevice::read() и QIODevice::write() позволяют считывать и записывать файлы блоками.
Продемонстрируем применение некоторых методов работы с файлами:
Если требуется считать или записать данные за один раз, то используют методы QIODevice::write() и QIODevice::readAll() . Все данные можно считать в объект класса QByteArray , а потом записать из него в другой файл:
Операция считывания всех данных сразу, в зависимости от размера файла, может занять много оперативной памяти, а значит, к этому следует прибегать только в случаях острой необходимости или в том случае, когда файлы занимают мало места. Расход памяти при считывании сразу всего файла можно значительно сократить при том условии, что файл содержит избыточную информацию. Тогда можно воспользоваться функциями сжатия qCompress() и qUncompress() , которые определены вместе с классом QByteArray . Эти функции получают, в качестве аргумента, объект класса QByteArray и возвращают, в качестве результата, новый объект класса QByteArray .
Для удаления файла класс QFile содержит статический метод remove() . В этот метод необходимо передать строку, содержащую полный или относительный путь удаляемого файла.
Читайте также: