文件设备
CreateFile:可以指定是同步还是异步,失败返回INVALID_HANDLE_VALUE而不是NULL,异步设备打开成功函数GetLaseError返回ERROR_IO_PENDING错误码
GetFileSIzeEx:获取文件的逻辑大小
SetEndOfFile:设置文件尾,可以利用其强制设置文件大小
HANDLE hFile = CreateFile(...);
LARGE_INTEGER liDistanceToMove;
liDistanceToMove.QuadPart=1024;
SetFilePointerEx(hFile, liDistanceToMove, NULL, FILE_BEGIN);
SetEndOfFile(hFile);
CloseHandle(hFile);
以上将文件设置为1024字节
ReadFile:读取文件
WriteFile:写文件
FlushFileBuffers:强制将缓冲数据写入到设备
CancelSynchronousIo(HANDLE hThread):将一个给定的线程尚未完成的同步I/O请求取消
以上是一些文件API的介绍下面来个例子
#include <Windows.h>
#include <iostream>
#include <process.h>
using namespace std;
unsigned WINAPI read( void *p )
{
return 0;
}
void main()
{
char cFileName[20] = "D://test.txt";
HANDLE hFile = CreateFile( cFileName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 );
if ( hFile == INVALID_HANDLE_VALUE )
cout << "create failure!!" << endl;
char DataBuffer[100] ;
memcpy( DataBuffer, "test data", strlen("test data") + 1 );
DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
DWORD dwBytesWritten = 0;
BOOL errorflag = WriteFile( hFile, DataBuffer, dwBytesToWrite, &dwBytesWritten, NULL );
if ( FALSE == errorflag )
{
cout << "write failure!!" << endl;
}
else
{
if ( dwBytesWritten != dwBytesToWrite )
{
cout << "not full write!!" << endl;
}
else
{
cout << "write successful!!" << endl;
}
}
FlushFileBuffers( hFile );
LARGE_INTEGER lisize = { 0 };
GetFileSizeEx( hFile, &lisize );
cout << "逻辑大小" << lisize.QuadPart << endl;
ULARGE_INTEGER ulisize = { 0 };
ulisize.LowPart = GetFileSize( hFile, &ulisize.HighPart );
cout << "物理大小" << ulisize.QuadPart << endl;
LARGE_INTEGER liDistanceToMove;
liDistanceToMove.QuadPart = 2048;
SetFilePointerEx( hFile, liDistanceToMove, NULL, FILE_BEGIN );
SetEndOfFile( hFile );
dwBytesWritten = 0;
ZeroMemory( DataBuffer, 100 );
liDistanceToMove.QuadPart = 5;
SetFilePointerEx( hFile, liDistanceToMove, NULL, FILE_BEGIN );
if ( ReadFile( hFile, DataBuffer, 4, &dwBytesWritten, NULL ) )
{
cout << "read successful!!" << endl;
}
else
cout << "read failure!!" << endl;
cout << DataBuffer << endl;
CloseHandle(hFile);
}