本文介绍了未缓冲的ReadFile(FILE_FLAG_NO_BUFFERING)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ReadFile函数的msdn文档说,如果使用 FILE_FLAG_NO_BUFFERING打开文件,则在尝试从文件读取时,数据缓冲区的地址必须以对齐的扇区大小(512)开始地点.但是,我能够使用未对齐扇区的缓冲区(缓冲区是使用C ++ new运算符分配的)来调用readfile,而没有任何明显的问题.我在Windows Server 2003 R2上测试了该代码,该代码是使用Visual C ++ 2008 SP1编译的:

The msdn doc for the ReadFile function says that if a file is opened with FILE_FLAG_NO_BUFFERING, then when attempting to read from the file, the data buffer's address must begin on a sector-size (512) aligned location. However, i was able to call readfile using a buffer NOT sector aligned (the buffer was allocated using the C++ new operator), without any obvious problem. I tested the code on Windows Server 2003 R2, it's compiled with Visual C++ 2008 SP1:

const int c_BufferSize == 64 * 1024;
void SyncReadDemo()
{
HANDLE h = CreateFile (L"c:\\ a.txt",GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_FLAG_NO_BUFFERING,0);
char ** buf == char [c_BufferSize]; //(char *)VirtualAlloc(NULL,c_BufferSize,MEM_COMMIT,PAGE_READWRITE);
int num;
BOOL 确定 = = ReadFile (h,buf,c_BufferSize,(LPDWORD)& num,NULL);
if( 确定 == 0)
{
errCode = GetLastError ();
std :: cout < < ; 错误代码 < < std :: endl;
}
否则
.{
std :: cout < < ; 数字 < < "读取的字节数 < < std :: endl;
}
delete [] buf; //VirtualFree(buf,0,MEM_RELEASE);
CloseHandle(h);
}
const int   c_BufferSize = 64*1024;  
 
void SyncReadDemo()  
{  
    HANDLE h    = CreateFile(L"c:\\a.txt", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, 0);  
    char  *buf  = new char[c_BufferSize]; //(char *)VirtualAlloc(NULL, c_BufferSize, MEM_COMMIT, PAGE_READWRITE);  
    int    num;  
    BOOL   ok   = ReadFile(h, buf, c_BufferSize, (LPDWORD)&num, NULL);  
    if(ok == 0)  
    {  
        int errCode = GetLastError();  
        std::cout <errCode <std::endl;  
    }  
    else  
    {  
        std::cout <num << " bytes read" <std::endl;  
    }  
    delete[] buf; // VirtualFree(buf, 0, MEM_RELEASE);  
    CloseHandle(h);  

推荐答案


这篇关于未缓冲的ReadFile(FILE_FLAG_NO_BUFFERING)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 02:04