|
HANDLEWINAPICreateFile(
_In_LPCTSTRlpFileName,
_In_DWORDdwDesiredAccess,
_In_DWORDdwShareMode,
_In_opt_LPSECURITY_ATTRIBUTESlpSecurityAttributes,
_In_DWORDdwCreationDisposition,
_In_DWORDdwFlagsAndAttributes,
_In_opt_HANDLEhTemplateFile
);
|
详情点击这里查看参数的说明:http://baike.baidu.com/view/1288759.htm
以下就是来用这个函数进行文件的读写操作:
1.读取文件数据:
HANDLE hOpenFile = (HANDLE)CreateFile("E:/a.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
DWORD RSize;
int fileSize = 0;
CHAR *pBuffer;
if (hOpenFile == INVALID_HANDLE_VALUE)
{
hOpenFile = NULL;
}
fileSize = GetFileSize(hOpenFile, NULL);
pBuffer = (CHAR *) malloc(fileSize);
ReadFile(hOpenFile, pBuffer, fileSize, &RSize, NULL);
free(pBuffer);
CloseHandle(hFile);
2.写入文件操作
DWORD dwBytesWritten = 0;
HANDLE hFile = CreateFile(
"E:/my.txt",//创建或打开的文件或设备的名称(这里是txt文件)。
GENERIC_WRITE,// 文件访问权限,写
0,//共享模式,这里设置0防止其他进程打开文件或设备
NULL,//SECURITY_ATTRIBUTES结构,安全描述,这里NULL代表默认安全级别
CREATE_ALWAYS,//对于存在或不存在的设置执行的操作,这里是始终创建
FILE_ATTRIBUTE_NORMAL,//设置文件的属性,里面有高速缓存的选项
NULL);
if (hOpenFile == INVALID_HANDLE_VALUE)
{
hOpenFile = NULL;
}
char * text = "Hello World!"
if(WriteFile(hFile,text,strlen(text)+1,&dwBytesWritten,NULL)==FALSE)
{
cout<<"WriteFile ERROR"<<endl;
return 1;
};
CloseHandle(hFile);