欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C/C++ Windows API:文件/文件夹

程序员文章站 2022-03-08 23:03:10
// fileoperationdemo.cpp : defines the entry point for the console application. // #include &...
// fileoperationdemo.cpp : defines the entry point for the console application.
//

#include "stdafx.h"
#include 

int main()
{
    bool ret;
    lpcwstr filepath1 = l"c:\\users\\chenjia2014\\desktop\\file_demo_test1.txt";
    lpcwstr filepath2 = l"c:\\users\\chenjia2014\\desktop\\file_demo_test2.txt";
    lpcwstr dirpath1 = l"c:\\users\\chenjia2014\\desktop\\dir_demo_test1";
    lpcwstr dirpath2 = l"c:\\users\\chenjia2014\\desktop\\dir_demo_test2";

    /*
    创建文件
    handle createfile(
      lpctstr lpfilename, //指向文件名的指针
      dword dwdesiredaccess, //访问模式(写/读), 如果为 generic_read 表示允许对设备进行读访问;如果为 generic_write 表示允许对设备进行写访问(可组合使用);如果为零,表示只允许获取与一个设备有关的信息
      dword dwsharemode, //共享模式, 0表示不共享; file_share_read 和/或 file_share_write 表示允许对文件进行共享访问
      lpsecurity_attributes lpsecurityattributes, //指向一个security_attributes安全属性结构的指针,定义了文件的安全特性(如果操作系统支持的话),默认为0
      dword dwcreationdisposition, //如何创建
      dword dwflagsandattributes, //文件属性
      handle htemplatefile //用于复制文件句柄, 如果不为零,则指定一个文件句柄。新文件将从这个文件中复制扩展属性
  );

    dwdesiredaccess long,下述常数之一:
    #define file_generic_read         (standard_rights_read     |\
        file_read_data           |\
        file_read_attributes     |\
        file_read_ea             |\
        synchronize)
    #define file_generic_write        (standard_rights_write    |\
        file_write_data          |\
        file_write_attributes    |\
        file_write_ea            |\
        file_append_data         |\
        synchronize)
    #define file_generic_execute      (standard_rights_execute  |\
        file_read_attributes     |\
        file_execute             |\
        synchronize)

    dwcreationdisposition long,下述常数之一:
    create_new 创建文件;如文件存在则会出错
    create_always 创建文件,会改写前一个文件
    open_existing 文件必须已经存在。由设备提出要求
    open_always 如文件不存在则创建它
    truncate_existing 讲现有文件缩短为零长度

    dwsharemode long,下述常数之一:
    #define file_share_read                 0x00000001
    #define file_share_write                0x00000002
    #define file_share_delete               0x00000004

    dwflagsandattributes long, 一个或多个下述常数
    file_attribute_archive 标记归档属性
    file_attribute_compressed 将文件标记为已压缩,或者标记为文件在目录中的默认压缩方式
    file_attribute_normal 默认属性
    file_attribute_hidden 隐藏文件或目录
    file_attribute_readonly 文件为只读
    file_attribute_system 文件为系统文件
    file_flag_write_through 操作系统不得推迟对文件的写操作
    file_flag_overlapped 允许对文件进行重叠操作
    file_flag_no_buffering 禁止对文件进行缓冲处理。文件只能写入磁盘卷的扇区块
    file_flag_random_access 针对随机访问对文件缓冲进行优化
    file_flag_sequential_scan 针对连续访问对文件缓冲进行优化
    file_flag_delete_on_close 关闭了上一次打开的句柄后,将文件删除。特别适合临时文件
    */
    dword dwdesiredaccess = generic_read | generic_write;
    dword dwsharemode = 0;
    lpsecurity_attributes lpsecurityattributes = 0;
    dword dwcreationdisposition = create_new;
    dword dwflagsandattributes = file_attribute_normal;
    handle htemplatefile = 0;
    handle handle = createfile(filepath1, dwdesiredaccess, dwsharemode, lpsecurityattributes, dwcreationdisposition, dwflagsandattributes, htemplatefile);
    printf("createfile -> handle=0x%x\n", handle);

    if (handle != invalid_handle_value) {

        filetime fcreationtime, flastaccesstime, flastwritetime;
        // getfiletime函数用来获得一个文件或目录的创建的时间、最后访问的时间以及最后修改的时间
        ret = getfiletime(handle, &fcreationtime, &flastaccesstime, &flastwritetime);
        if (ret == 0) {
            printf("getfiletime fail(%d)\n", getlasterror());
        }
        else {
            printf("getfiletime -> %d\n", ret);
        }

        /*
        根据一个filetime结构的内容,装载一个systemtime结构。
        winbaseapi _success_(return != false) bool winapi filetimetosystemtime(
            _in_ const filetime * lpfiletime,
            _out_ lpsystemtime lpsystemtime
        );
        */
        systemtime syscreationtime, syslastaccesstime, syslastwritetime;
        ret = filetimetosystemtime(&fcreationtime, &syscreationtime);
        if (ret == 0) {
            printf("filetimetosystemtime creationtime fail(%d)\n", getlasterror());
        }
        else {
            printf("filetimetosystemtime creationtime -> %d\n", ret);
            printf("%4d年%2d月%2d日,%2d:%2d:%2d\n", syscreationtime.wyear, syscreationtime.wmonth, syscreationtime.wday, syscreationtime.whour, syscreationtime.wminute, syscreationtime.wsecond);
        }
        ret = filetimetosystemtime(&flastaccesstime, &syslastaccesstime);
        if (ret == 0) {
            printf("filetimetosystemtime lastaccesstime fail(%d)\n", getlasterror());
        }
        else {
            printf("filetimetosystemtime lastaccesstime -> %d\n", ret);
            printf("%4d年%2d月%2d日,%2d:%2d:%2d\n", syslastaccesstime.wyear, syslastaccesstime.wmonth, syslastaccesstime.wday, syslastaccesstime.whour, syslastaccesstime.wminute, syslastaccesstime.wsecond);
        }
        ret = filetimetosystemtime(&flastwritetime, &syslastwritetime);
        if (ret == 0) {
            printf("filetimetosystemtime lastwritetime fail(%d)\n", getlasterror());
        }
        else {
            printf("filetimetosystemtime lastwritetime -> %d\n", ret);
            printf("%4d年%2d月%2d日,%2d:%2d:%2d\n", syslastwritetime.wyear, syslastwritetime.wmonth, syslastwritetime.wday, syslastwritetime.whour, syslastwritetime.wminute, syslastwritetime.wsecond);
        }

        //用完要记得关闭,否则其他操作会失败,getlasterror()=32 => 进程无法访问文件,因为另一个程序正在使用此文件。
        closehandle(handle);
    }

    /*
    复制文件
    bool winapi copyfile(
        _in_ lpctstr lpexistingfilename,
        _in_ lpctstr lpnewfilename,
        _in_ bool    bfailifexists
    );
    return 失败返回0,成功返回非0。
    */
    ret = copyfile(filepath1, filepath2, true);
    if (ret == 0) {
        printf("copyfile fail(%d)\n", getlasterror());
    }
    else {
        printf("copyfile -> %d\n", ret);
    }

    /*
    删除文件
    bool deletefile(
        lpcstrlpfilename//要删除的文件名的指针
    );
    return 失败返回0,成功返回非0。如果程序尝试删除一个不存在的文件。getlasterror返回error_file_not_found。如果文件是只读 的,则getlasterror返回error_access_denied
    */
    ret = deletefile(filepath1);
    if (ret == 0) {
        printf("deletefile fail(%d)\n", getlasterror());
    }
    else {
        printf("deletefile -> %d\n", ret);
    }

    /*
    移动一个存在的文件或者目录(包括子目录)
    winbaseapi bool winapi movefilew(
        _in_ lpcwstr lpexistingfilename,
        _in_ lpcwstr lpnewfilename
    );
    return 失败返回0,成功返回非0。
    */
    ret = movefile(filepath2, filepath1);
    if (ret == 0) {
        printf("movefile fail(%d)\n", getlasterror());
    }
    else {
        printf("movefile -> %d\n", ret);
    }

    /*
    winbaseapi dword winapi getfileattributesw(
        _in_ lpcwstr lpfilename
    );

    #define file_attribute_readonly             0x00000001
    #define file_attribute_hidden               0x00000002
    #define file_attribute_system               0x00000004
    #define file_attribute_directory            0x00000010
    #define file_attribute_archive              0x00000020
    #define file_attribute_device               0x00000040
    #define file_attribute_normal               0x00000080
    #define file_attribute_temporary            0x00000100
    #define file_attribute_sparse_file          0x00000200
    #define file_attribute_reparse_point        0x00000400
    #define file_attribute_compressed           0x00000800
    #define file_attribute_offline              0x00001000
    #define file_attribute_not_content_indexed  0x00002000
    #define file_attribute_encrypted            0x00004000
    #define file_attribute_integrity_stream     0x00008000
    #define file_attribute_virtual              0x00010000
    #define file_attribute_no_scrub_data        0x00020000
    #define file_attribute_ea                   0x00040000
    */
    dword attr = getfileattributes(filepath1);
    if (attr == invalid_file_attributes) {
        printf("getfileattributes fail(%d)", getlasterror());
    }
    else {
        printf("getfileattributes -> 0x%x\n", attr);
    }

    deletefile(filepath1);

    /*
    创建文件夹(注意: 目录没有复制操作)
    winbaseapi bool winapi createdirectoryw(
        _in_ lpcwstr lppathname,
        _in_opt_ lpsecurity_attributes lpsecurityattributes
    );
    return 失败返回0,成功返回非0。
    */
    ret = createdirectory(dirpath1, 0);
    if (ret == 0) {
        printf("createdirectory fail(%d)\n", getlasterror());
    }
    else {
        printf("createdirectory -> %d\n", ret);
    }

    /*
    删除目录(注意:目录必须为空,否则会报145错误)
    winbaseapi bool winapi removedirectoryw(
        _in_ lpcwstr lppathname
    );
    */
    ret = removedirectory(dirpath1);
    if (ret == 0) {
        printf("removedirectory fail(%d)\n", getlasterror());
    }
    else {
        printf("removedirectory -> %d\n", ret);
    }

    system("pause");
    return 0;
}