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));
}

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...