Изменить дату файла lastModified / lastAccessed / created в Qt - PullRequest
1 голос
/ 18 июня 2020

У меня есть приложение, которое копирует некоторые файлы, но во время процедуры копирования даты последнего изменения и c меняются на текущие дату и время. На некоторых форумах я вижу, что предлагается использовать вызов SETFILETIME из fileapi.h, как указано здесь в MS docs .

Однако быстрый поиск показывает, что эти функции доступны здесь, в QFileDevice , где можно использовать функцию setFileTime со следующим перечислением FileTime . Обратите внимание: QFile или QFileInfo не позволяет изменять эти даты и время, а только читает эти даты и время.

QFileDevice :: FileAccessTime 0 Когда файл был выполнен последний доступ (например, прочитан или записан). QFileDevice :: FileBirthTime 1 Когда файл был создан (может не поддерживаться UNIX). QFileDevice :: FileMetadataChangeTime 2 Когда в последний раз были изменены метаданные файла. QFileDevice :: FileModificationTime 3 Время последнего изменения файла.

Как я могу получить экземпляр этого QFileDevice, скажем, из объекта QFileInfo или даже из объекта QFile (в этом case, QFile наследуется от QFileDevice - поможет ли, например, static_cast <> ()?

В качестве альтернативы, лучше использовать Windows FileAPI.h - как я могу сделать это, скажем, из какого-то файла местоположение и QDateTime, чтобы изменить created или lastModified время?

1 Ответ

2 голосов
/ 18 июня 2020

Должен признать, что я заметил QFile :: setFileTime () в первый раз из-за вопроса OP. (У меня никогда не было необходимости настраивать временные метки любого файла, написанного моим ПО.) Из любопытства я попытался разгадать это.

Вот что я получил:

// Qt header:
#include <QtCore>

// main application
int main(int argc, char **argv)
{
  auto showTimeStamps = [](const QFile &file) {
    qDebug() << "File time stamps of" << file.fileName();
    QFileInfo fileInfo(file);
    qDebug() << "birthTime()   :" << fileInfo.birthTime();
    qDebug() << "lastModified():" << fileInfo.lastModified();
    qDebug() << "lastAccessed():" << fileInfo.lastRead();
  };

  qDebug() << "Qt Version:" << QT_VERSION_STR;
  { QFile file("test.txt");
    // create test file
    qDebug() << "Write test.txt...";
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
      qDebug() << "Failed to create test.txt!";
      return 1;
    }
    if (file.write("Test.\n") < 0) {
      qDebug() << "Failed to write to test.txt!";
      return 1;
    }
    file.close();
    qDebug() << "Done.";
    // check file time stamps initially
    showTimeStamps(file);
    // manipulate file time stamps
    const QDateTime timeStamp(QDate(1970, 5, 1), QTime(6, 0));
    qDebug() << "Modify time stamp of creation of test.txt:";
    if (!file.open(QIODevice::Append | QIODevice::Text)) {
      qDebug() << "Failed to open test.txt!";
      return 1;
    }
    if (!file.setFileTime(timeStamp, QFileDevice::FileBirthTime)) {
      qDebug() << "Failed to modify create time!";
      return 1;
    }
    file.close();
    showTimeStamps(file);
    qDebug() << "Modify time stamp of last modification of test.txt:";
    if (!file.open(QIODevice::Append | QIODevice::Text)) {
      qDebug() << "Failed to open test.txt!";
      return 1;
    }
    if (!file.setFileTime(timeStamp, QFileDevice::FileModificationTime)) {
      qDebug() << "Failed to modify last modified time!";
      return 1;
    }
    file.close();
    showTimeStamps(file);
    qDebug() << "Modify time stamp of last access of test.txt:";
    file.setFileTime(timeStamp, QFileDevice::FileAccessTime);
    if (!file.open(QIODevice::Append | QIODevice::Text)) {
      qDebug() << "Failed to open test.txt!";
      return 1;
    }
    if (!file.setFileTime(timeStamp, QFileDevice::FileAccessTime)) {
      qDebug() << "Failed to modify last access time!";
      return 1;
    }
    file.close();
    showTimeStamps(file);
  }
  // bail out to enable check in File Explorer afterwards
  return 0;
  // delete test file
  { qDebug() << "Delete test.txt...";
    if (!QFile::remove("test.txt")) {
      qDebug() << "Failed to delete test.txt!";
      return 1;
    }
    qDebug() << "Done.";
  }
}

Вывод:

Qt Version: 5.13.0
Write test.txt...
Done.
File time stamps of "test.txt"
birthTime()   : QDateTime(2020-06-18 08:42:09.983 Mitteleuropõische Sommerzeit Qt::LocalTime)
lastModified(): QDateTime(2020-06-18 08:42:09.984 Mitteleuropõische Sommerzeit Qt::LocalTime)
lastAccessed(): QDateTime(2020-06-18 08:42:09.983 Mitteleuropõische Sommerzeit Qt::LocalTime)
Modify time stamp of creation of test.txt:
File time stamps of "test.txt"
birthTime()   : QDateTime(1970-05-01 06:00:00.000 Mitteleuropõische Sommerzeit Qt::LocalTime)
lastModified(): QDateTime(2020-06-18 08:42:09.984 Mitteleuropõische Sommerzeit Qt::LocalTime)
lastAccessed(): QDateTime(2020-06-18 08:42:09.983 Mitteleuropõische Sommerzeit Qt::LocalTime)
Modify time stamp of last modification of test.txt:
File time stamps of "test.txt"
birthTime()   : QDateTime(1970-05-01 06:00:00.000 Mitteleuropõische Sommerzeit Qt::LocalTime)
lastModified(): QDateTime(1970-05-01 06:00:00.000 Mitteleuropõische Sommerzeit Qt::LocalTime)
lastAccessed(): QDateTime(2020-06-18 08:42:09.983 Mitteleuropõische Sommerzeit Qt::LocalTime)
Modify time stamp of last access of test.txt:
File time stamps of "test.txt"
birthTime()   : QDateTime(1970-05-01 06:00:00.000 Mitteleuropõische Sommerzeit Qt::LocalTime)
lastModified(): QDateTime(1970-05-01 06:00:00.000 Mitteleuropõische Sommerzeit Qt::LocalTime)
lastAccessed(): QDateTime(1970-05-01 06:00:00.000 Mitteleuropõische Sommerzeit Qt::LocalTime)

Впоследствии я проверил отметки времени в Windows проводнике:

snapshot of File Properties for test.txt

Итак , Мне интересно узнать о претензии OP

Примечание, QFile или QFileInfo не позволяют изменять эти даты и время, а только читают эти даты и время.

Я ожидал это фактическое намерение QFile :: setFileTime () , и, похоже, он работает правильно на моей стороне.

...