Categories
不学无术

WINDOWS API 文件操作

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参数组合起来指定了加锁区域的大小。如果对文件进行了加锁后,当确定程序不在使用时,最好调用UnlockFile显式的解锁,虽然操作系统会对其自动解锁,但操作系统解锁的用的时间取决于当前可用的系统资源,所以有可能造成文件的无法访问。

5. 获取文件信息

  DWORD GetFileType(
  HANDLE hFile   // handle to file
);

获取文件类型,其返回值可参考MSDN。

  DWORD GetFileSize(
  HANDLE hFile,           // handle to file
  LPDWORD lpFileSizeHigh  // high-order word of file size
);

获取文件的大小,函数执行成功将返回文件大小的低双字,如果lpFileSizeHigh参数不是NULL,函数将文件大小的高双字放入它指向的DWORD变量中

  DWORD GetFileAttributes(
  LPCTSTR lpFileName   // name of file or directory
);

如果要查看文件或者目录的属性,可以使用GetFileAttributes函数,它会返回一系列的FAT风格属性信息。返回值可参考MSDN。

  BOOL SetFileAttributes(
  LPCTSTR lpFileName,      // file name
  DWORD dwFileAttributes   // attributes
);

设置文件属性

  BOOL GetFileTime(
  HANDLE hFile,                 // handle to file
  LPFILETIME lpCreationTime,    // creation time
  LPFILETIME lpLastAccessTime// last access time
  LPFILETIME lpLastWriteTime    // last write time
);

获取文件时间,有三个文件时间可供获取:创建时间、最后访问时间、最后写时间。参数具体信息可参考MSDN

  BOOL GetFileInformationByHandle(
  HANDLE hFile,                                  // handle to file
  LPBY_HANDLE_FILE_INFORMATION lpFileInformation // buffer
);

获取所有文件信息,该函数能够获取文件的所有信息,如大小,属性等,另外还有一些其它信息,如文件卷标,索引和链接信息。返回信息保存在lpFileInformation所指向的BY_HANDLE_FILE_INFORMATION中

typedef struct _BY_HANDLE_FILE_INFORMATION {
  DWORD    dwFileAttributes;
  FILETIME  ftCreationTime;
  FILETIME  ftLastAccessTime;
  FILETIME  ftLastWriteTime;
  DWORD    dwVolumeSerialNumber;
  DWORD    nFileSizeHigh;
  DWORD    nFileSizeLow;
  DWORD    nNumberOfLinks;
  DWORD    nFileIndexHigh;
  DWORD    nFileIndexLow;
} BY_HANDLE_FILE_INFORMATION, *PBY_HANDLE_FILE_INFORMATION;
关于此结构的具体信息参考MSDN。
  DWORD GetFullPathName(
  LPCTSTR lpFileName// file name
  DWORD nBufferLength, // size of path buffer
  LPTSTR lpBuffer,     // path buffer
  LPTSTR *lpFilePart   // address of file name in path
);
获取文件的完整路径,需要提醒的是:只有当该文件在当前目录下,结果才正确。如果要得到真正的路径。应该用GetModuleFileName函数。
  DWORD GetModuleFileName(
  HMODULE hModule,    // handle to module
  LPTSTR lpFilename// path buffer
  DWORD nSize         // size of buffer
);

  hModule HMODULE 装载一个程序实例的句柄。如果该参数为NULL,该函数返回该当前应用程序全路径。

   lpFileName LPTSTR 是你存放返回的名字的内存块的指针,是一个输出参数 nSize DWORD ,装载到缓冲区lpFileName的最大值

如果返回为成功,将在lpFileName的缓冲区当中返回相应模块的路径,如果所为的nSize过小,哪么返回仅按所设置缓冲区大小返回相应字符串内容。如果函数失败,返回值将为0,并返回GetLastError异常代码。

  DWORD GetModuleFileNameEx(
  HANDLE hProcess,    // handle to process
  HMODULE hModule,    // handle to module
  LPTSTR lpFilename// path buffer
  DWORD nSize         // maximum characters to retrieve
);
与上一个函数的不同在于多了一个与进程相关的句柄,如果为NULL则lpFilename的值为当前程序的全路径。
  DWORD GetTempPath(
  DWORD nBufferLength// size of buffer
  LPTSTR lpBuffer       // path buffer
);
获取Windows临时文件路径。
  UINT GetTempFileName(
  LPCTSTR lpPathName,      // directory name
  LPCTSTR lpPrefixString// file name prefix
  UINT uUnique,            // integer
  LPTSTR lpTempFileName    // file name buffer
);
在Windows临时目录下创建一个唯一的临时文件。具体参数信息参考MSDN。
 
 
WINSHELLAPI DWORD WINAPI SHGetFileInfo(
LPCTSTR pszPath, 
DWORD dwFileAttributes, 
SHFILEINFO FAR *psfi, 
UINT cbFileInfo, 
UINT uFlags );
获取系统文件信息,如文件,文件夹,目录,驱动器目录

 pszPath 参数:指定的文件名。

  当uFlags的取值中不包含 SHGFI_PIDL时,可直接指定;

  当uFlags的取值中包含 SHGFI_PIDL时pszPath要通过计算获得,不能直接指定;

  dwFileAttributes参数:文件属性。

  仅当uFlags的取值中包含SHGFI_USEFILEATTRIBUTES时有效,一般不用此参数;

  psfi 参数:返回获得的文件信息,是一个记录类型,有以下字段:

  _SHFILEINFOA = record

  hIcon: HICON; { out: icon } //文件的图标句柄

  iIcon: Integer; { out: icon index } //图标的系统索引号

  dwAttributes: DWORD; { out: SFGAO_ flags } //文件的属性值

  szDisplayName: array [0..MAX_PATH-1] of AnsiChar; { out: display name (or path) } //文件的显示名

  szTypeName: array [0..79] of AnsiChar; { out: type name } //文件的类型名

  end;

  cbFileInfo 参数:psfi的比特值;

  uFlags 参数:指明需要返回的文件信息标识符,常用的有以下常数:

  SHGFI_ICON; //获得图标

  SHGFI_DISPLAYNAME; //获得显示名

  SHGFI_TYPENAME; //获得类型名

  SHGFI_ATTRIBUTES; //获得属性

  SHGFI_LARGEICON; //获得大图标

  SHGFI_SMALLICON; //获得小图标

  SHGFI_PIDL; // pszPath是一个标识符

  函数SHGetFileInfo()的返回值也随uFlags的取值变化而有所不同。

  可见通过调用SHGetFileInfo()可以由psfi参数得到文件的图标句柄。但要注意在uFlags参数中不使用SHGFI_PIDL时,SHGetFileInfo()不能获得“我的电脑”等虚似文件夹的信息。

  应该注意的是,在调用SHGetFileInfo()之前,必须使用 CoInitialize 或者OleInitialize 初始化COM,否则表面上能够使用,但是会造成不安全或者丧失部分功能

6. 文件拷贝、删除、移动

  BOOL CopyFile(
  LPCTSTR lpExistingFileName, // name of an existing file
  LPCTSTR lpNewFileName,      // name of new file
  BOOL bFailIfExists          // operation if file exists
);
 
  BOOL CopyFileEx(
  LPCTSTR lpExistingFileName,           // name of existing file
  LPCTSTR lpNewFileName,                // name of new file
  LPPROGRESS_ROUTINE lpProgressRoutine, // callback function
  LPVOID lpData,                        // callback parameter
  LPBOOL pbCancel,                      // cancel status
  DWORD dwCopyFlags                     // copy options
);

文件拷贝函数,CopyFileEx函数附加功能是允许指定一个回调函数,在拷贝过程中,函数每拷贝完一部分数据,就会调用回调函数,回调函数则可由用户指定操作。

  BOOL DeleteFile(
  LPCTSTR lpFileName   // file name
);

文件删除函数,当文件不存在或者文件属性为只读,函数会执行失败,对于只读文件,在删除前就去掉其只读属性。用DeleteFile函数删除的文件不会被放到回收站,它们将永远丢失。

  BOOL MoveFile(
  LPCTSTR lpExistingFileName, // file name
  LPCTSTR lpNewFileName       // new file name
);
  BOOL MoveFileEx(
  LPCTSTR lpExistingFileName// file name
  LPCTSTR lpNewFileName,       // new file name
  DWORD dwFlags                // move options
);

文件移动函数,其主要功能都是用来移动一个存在的文件或目录,当需要指定文件如何移动时,则用MoveFileEx函数,其dwFlags指定文件移动方式,具体说明可参考MSDN。

7. 文件查找

  HANDLE FindFirstFile(
  LPCTSTR lpFileName,               // file name
  LPWIN32_FIND_DATA lpFindFileData  // data buffer
);
  HANDLE FindFirstFileEx(
  LPCTSTR lpFileName,              // file name
  FINDEX_INFO_LEVELS fInfoLevelId, // information level
  LPVOID lpFindFileData,           // information buffer
  FINDEX_SEARCH_OPS fSearchOp,     // filtering type
  LPVOID lpSearchFilter,           // search criteria
  DWORD dwAdditionalFlags          // reserved
);

该函数到一个文件夹(包括子文件夹)去搜索指定文件 如果要使用附加属性去搜索文件的话 可以使用FindFirstFileEx函数。HANDLE hFindFile搜索的文件句柄 函数执行的时候搜索的是此句柄的下一文件

  LPWIN32_FIND_DATA lpFindFileData 指向一个用于保存文件信息的结构体

函数调用成功后,其返回值可用作FindNextFile或FindClose函数的参数。

  BOOL FindNextFile(
  HANDLE hFindFile,                // search handle
  LPWIN32_FIND_DATA lpFindFileData // data buffer
);

在FindFirstFile函数调用成功后继续查找文件。

8. 压缩文件操作

  INT LZOpenFile(
  LPTSTR lpFileName,       // file name
  LPOFSTRUCT lpReOpenBuf// file information buffer
  WORD wStyle              // action to take
);

创建,打开,删除压缩文件。参数信息参考MSDN。

  VOID LZClose(
  INT hFile   // LZ file handle
);

关闭压缩文件,参数为LPOpenFile返回的值。

  LONG LZCopy(
  INT hfSource// LZ file handle for source file
  INT hfDest     // LZ file handle for destination file
);

复制压缩文件并在处理过程中展开,函数的两个参数都可以用LPOpenFile函数得到,只要指定LPOpenFile函数wStyle的不同值。

INT GetExpandedName(
  LPTSTR lpszSource// name of compressed file
  LPTSTR lpszBuffer   // original file name
);

从压缩文件中返回文件名称,参数信息参考MSDN。

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.