• Windows文件操作基础代码


    Windows文件操作基础代码

     

        Windows下对文件进行操作使用的一段基础代码File.h,首先是File类定义:

    #pragma once
    #include<Windows.h>
    #include<assert.h>
    class File
    {
        HANDLE hFile;//文件句柄
    public:
        void open(LPCWSTR fileName);
        int read(char*data,int len);
        void movefp(long disp,int type);
        int write(char*data,int len);
        void close();
        static void copy(LPCWSTR src,LPCWSTR des);
        static void move(LPCWSTR src,LPCWSTR des);
        static void del(LPCWSTR name);
    };

       File类的实现如下:

       1.打开文件:这里文件打开方式为读写、文件不存在则创建。

    void File::open(LPCWSTR fileName)
    {
        //使用CreatFile以读写方式打开一个文件
        hFile=CreateFile(fileName,//文件名
            GENERIC_WRITE|GENERIC_READ,//读写权限
            FILE_SHARE_READ|FILE_SHARE_WRITE//共享读写权限
            ,NULL//安全特性
            ,OPEN_ALWAYS//CREATE_NEW-存在出错,CREATE_ALWAYS-改写存在文件,OPEN_EXISTING-不存在出错,OPEN_ALWAYS-不存在创建
            
    //TRUNCATE_EXISTING-将现有文件长度缩短为0
            ,FILE_ATTRIBUTE_NORMAL//FILE_ATTRIBUTE^X,X_ARCHIVE-标记归档,X_NORMAL-默认,X_HIDDEN-隐藏,X_READONLY-只读,X_SYSTEM-系统
            ,NULL);
        assert(hFile!=INVALID_HANDLE_VALUE);
    }

       2.关闭文件:

    void File::close()
    {
        CloseHandle(hFile);
    }

       3.读文件:
    int File::read(char*data,int len)
    {
        DWORD dwWrite;
        bool rslt=ReadFile(hFile,data,len,&dwWrite,NULL);
        assert(rslt);
        return dwWrite;
    }
       4.写文件:
    int File::write(char*data,int len)
    {
        DWORD dwWrite;
        bool rslt=WriteFile(hFile,data,len,&dwWrite,NULL);
        assert(rslt);
        return dwWrite;
    }
       5.移动文件指针:
    void File::movefp(long disp,int type)
    {
        SetFilePointer(hFile,disp,NULL,type);
    }
       6.其他文件操作API,复制、移动、删除(可以扩展):
    void File::copy(LPCWSTR src,LPCWSTR des)
    {
        assert(CopyFile(src,des,true));
    }
    void File::move(LPCWSTR src,LPCWSTR des)
    {
        assert(MoveFile(src,des));
    }
    void File::del(LPCWSTR name)
    {
        assert(DeleteFile(name));
    }
  • 相关阅读:
    Action/Service/DAO简介 一
    Python中的Nonetype类型怎么判断?
    idea 中使用maven命令
    python-字符串中含有变量的表示方法
    python-configparser模块,读取配置文件
    python json 和 dict
    python interpreter解释器设置
    python写入数据到excel-xlwt模块(不能修改,每次写入全覆盖)
    pymongo问题集合
    excel表操作使用记录
  • 原文地址:https://www.cnblogs.com/fanzhidongyzby/p/2617239.html
Copyright © 2020-2023  润新知