您的位置:首页 > 编程语言 > Qt开发

Qt -Ftp下载之修改文件属性(修改时间,访问时间)

2017-12-22 09:52 1306 查看
来自:http://blog.csdn.net/tracybochen/article/details/8550184

报文分发程序需提供这么一个功能: Qt对下载文件的时间修改(ftp,http下载)

当我们下载一个文件到本地后,文件的相关属性(如修改时间,创建时间,访问时间)都会修改为下载后的系统时间。

而报文分发程序中想让下载到本地的文件保留源文件的修改时间,此时我们必须手动对文件的属性就行操作。

但是Qt做不了,只能通过在Qt程序中调用系统命令。可以直接包括#include<windows.h>或者#include <sys/utime.h>然后调用系统函数。

Qt中没有相应的函数,修改文件时间这种操作是和平台相关的,所以如果程序是需要跨平台的话,需要进行条件编译。不同的平台下调用不同的系统函数进行设置。

其中涉及的API:

windows下:_utime()

linux: utime()

下面介绍实现需要的函数:

PS: 不同操作系统下实现都很类似,只是函数名变了个样。

int _utime( const char *filename, struct _utimbuf *times );//Windows

int utime ( const char *filename, struct utimbuf *times );//linux

形参介绍:

filename 文件路径

times 保存时间数值的指针

_utimbuf结构体的

(Windows)

struct _utimbuf

{

time_t actime; /* Access time */

time_t modtime; /* Modification time */

};

(other OS)

struct utimbuf

{

time_t actime;

time_t modtime;

};

tm结构体 储存时间信息

struct tm {

int tm_sec; /* seconds after the minute - [0,59] */

int tm_min; /* minutes after the hour - [0,59] */

int tm_hour; /* hours since midnight - [0,23] */

int tm_mday; /* day of the month - [1,31] */

int tm_mon; /* months since January - [0,11] */

int tm_year; /* years since 1900 */

int tm_wday; /* days since Sunday - [0,6] */

int tm_yday; /* days since January 1 - [0,365] */

int tm_isdst; /* daylight savings time flag */

};

之间还涉及到将QString类型转换为const char*类型,作为_utime()的第一个形参。 

QString str= QTextCodec::codecForLocale()->toUnicode("测试12345678");

QByteArray ary;

ary.append(str);

char *fileName = ary.data();

//4.5 修改本地temp下文件的修改时间
void ExcuThread::modifyDownFileTime(const QDateTime& dtLastModify,const QString& sFilePath)
{
    qApp->processEvents();
    if(sFilePath.isEmpty() || !dtLastModify.isValid() || dtLastModify.isNull())
        return;

    int aYear = dtLastModify.date().year() - 1900;
    int aMonth = dtLastModify.date().month() - 1;
    int aDay = dtLastModify.date().day();
    int aHour = dtLastModify.time().hour();
    int aMinute = dtLastModify.time().minute();
    int aSec = dtLastModify.time().second();
    qDebug()<<"时间1:"<<aYear<<aMonth<<aDay<<aHour<<aMinute<<aSec;
    struct tm tma = {0};
    tma.tm_year = aYear;
    tma.tm_mon = aMonth;
    tma.tm_mday = aDay;
    tma.tm_hour = aHour;
    tma.tm_min = aMinute;
    tma.tm_sec = aSec;
    tma.tm_isdst = 0;
#ifdef Q_WS_WIN
    struct _utimbuf ut;
#else
    struct utimbuf ut;
#endif
    ut.modtime = mktime(&tma);
    QString str= QTextCodec::codecForLocale()->toUnicode(sFilePath.toAscii());
    QByteArray ary;
    ary.append(str);
    char *fileName = ary.data();
    qDebug()<<ary<<fileName;//

#ifdef Q_WS_WIN
    if( _utime(fileName, &ut ) == -1 )
#else
    if( utime(fileName, &ut ) == -1 )
#endif
      qDebug() << " failed" ;
    else
      qDebug()<< "File time modified\n";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Qt
相关文章推荐