WINDOWS文件操作
1. 打开和关闭文件:
HANDLE CreateFile( LPCTSTR lpFileName, // file name DWORD dwDesiredAccess, // access mode DWORD dwShareMode, // share mode LPSECURITY_ATTRIBUTES lpSecurityAttributes, // SD DWORD dwCreationDisposition, // how to create DWORD dwFlagsAndAttributes, // file attributes HANDLE hTemplateFile // handle to template file ; CreateFile函数相当强大,Windows下的底层设备差不多都是由它打开的。它可以创建或打开文件、目录、物理磁盘、控制台缓冲区、邮槽和管道等。具体参考MSDN。
2. 移动文件指针:
DWORD SetFilePointer( HANDLE hFile, // handle to file LONG lDistanceToMove, // bytes to move pointer PLONG lpDistanceToMoveHigh, // bytes to move pointer DWORD dwMoveMethod // starting point ;
设置文件结尾标志:
BOOL SetEndOfFile( HANDLE hFile // handle to file ;
该函数移动指定文件的结束标志到文件指针指向的位置。可用来截断或者扩展文件,如果文件扩展,旧的EOF位置和新的EOF位置间的内容是未定义的。参考MSDN。
3. 文件读写:
BOOL ReadFile( HANDLE hFile, // handle to file LPVOID lpBuffer, // data buffer DWORD nNumberOfBytesToRead, // number of bytes to read LPDWORD lpNumberOfBytesRead, // number of bytes read LPOVERLAPPED lpOverlapped // overlapped buffer ;
文件读取函数
BOOL WriteFile( HANDLE hFile, // handle to file LPCVOID lpBuffer, // data buffer DWORD nNumberOfBytesToWrite, // number of bytes to write LPDWORD lpNumberOfBytesWritten, // number of bytes written LPOVERLAPPED lpOverlapped // overlapped buffer ;
文件写入函数,当Windows文件写文件时,写的的文件通常被Windows暂时保存在内部的高速缓存中,等合适的时间再一并写入磁盘,可以调用FlushFileBuffer(HANDLE hFile // handle to file)函数来清空数据缓冲区 这两个函数可以同步读写文件,又可以异步读写文件。另外两个函数ReadFileEx和WriteFileEx只能异步读写文件。比上面函数多了一个参数 : LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // completion routine
4. 文件锁定与解锁:
BOOL LockFile( HANDLE hFile, // handle to file DWORD dwFileOffsetLow, // low-order word of offset DWORD dwFileOffsetHigh, // high-order word of offset DWORD nNumberOfBytesToLockLow, // low-order word of length DWORD nNumberOfBytesToLockHigh // high-order word of length ;
BOOL UnlockFile( HANDLE hFile, // handle to file DWORD dwFileOffsetLow, // low-order word of start DWORD dwFileOffsetHigh, // high-order word of start DWORD nNumberOfBytesToUnlockLow, // low-order word of length DWORD nNumberOfBytesToUnlockHigh // high-order word of length ;
这两个函数用于当对文件数据一致性要求较高时,为防止程序在写入的过程中其他进程刚好在读取写入的内容,可以对已打开文件的某个部分进行加锁。 函数参数中dwFileOffsetLow和dwFileOffsetHigh参数组合起来指定了加锁区域的开始位置,nNumberOfBytesTLockLow和nNumberOfBytesToLockHigh参数组