同步设备IO

文件设备

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


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值