首页 > 代码库 > 如何访问超长文件

如何访问超长文件

    现在,又回归到代码编写了。
    其实,安安静静地享受编码的过程,是一个很美好的旅程,从此以后,就尽情享受这一过程吧。
    现在,就遇到了在Windows上如何访问和操作超长文件(长度超过256)的问题。此前一直使用open、read、write等Windows原始开发接口,为照顾和Linux、Unix等接口类型的兼容性,没有使用Win32的SDK接口,这下搞不定了。
    经过本次调研,发现访问超长文件名的方法,基本上有两种
一、将文件名缩短成8.3格式,继续使用原始开发接口来操作

The GetShortPathName function retrieves the short path form of a specified input path.

DWORD GetShortPathName(
  LPCTSTR lpszLongPath,  // null-terminated path string
  LPTSTR lpszShortPath,  // short form buffer
  DWORD cchBuffer        // size of short form buffer
);

Parameters

lpszLongPath
[in] Pointer to a null-terminated path string. The function retrieves the short form of this path.

Windows NT/2000/XP: In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to nearly 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see File Name Conventions.

Windows 95/98/Me: This string must not exceed MAX_PATH characters.

lpszShortPath
[out] Pointer to a buffer to receive the null-terminated short form of the path specified by lpszLongPath.
cchBuffer
[in] Specifies the size, in TCHARs, of the buffer pointed to by lpszShortPath.

Return Values

If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpszShortPath, not including the terminating null character.

If the lpszShortPath buffer is too small to contain the path, the return value is the size of the buffer, in TCHARs, required to hold the path. Therefore, if the return value is greater than cchBuffer, call the function again with a buffer that is large enough to hold the path.

If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError.

    从lpszLongPath参数的说明可以看出,GetShortPathNameW函数,可以对目录或文件名进行缩短,但有个前提是目录或文件名必须存在。即

    1)对于已经存在的目录或文件,适用;
    2)对于不存在的目录或文件(新建目录或文件时),不适用;
 
二、借用Win32接口来实现对超长文件名的文件或目录的操作
    其中,涉及到如下的函数
FunctionDescription
AreFileApisANSIDetermines whether the file I/O functions are using the ANSI or OEM character set code page.
CancelIoCancels all pending I/O operations that were issued by the calling thread for the specified file handle.
CloseHandleCloses an open object handle.
CopyFileCopies an existing file to a new file.
CopyFileExCopies an existing file to a new file.
CopyProgressRoutineAn application-defined callback function used with CopyFileEx and MoveFileWithProgress.
CreateDirectoryCreates a new directory.
CreateDirectoryExCreates a new directory with the attributes of a specified template directory.
CreateFileCreates or opens a file object.
CreateIoCompletionPortCreates and I/O completion port or associates an instance of an opened file with a newly created or an existing I/O completion port.
DefineDosDeviceDefines, redefines, or deletes MS-DOS device names.
DeleteFileDeletes an existing file.
FileIOCompletionRoutineAn application-defined callback function used with ReadFileEx and WriteFileEx.
FindCloseCloses the specified search handle.
FindCloseChangeNotificationStops change notification handle monitoring.
FindFirstChangeNotificationCreates a change notification handle.
FindFirstFileSearches a directory for a file whose name matches the specified file name.
FindFirstFileExSearches a directory for a file whose name and attributes match those specified.
FindNextChangeNotificationRequests that the operating system signal a change notification handle the next time it detects an appropriate change.
FindNextFileContinues a file search.
FlushFileBuffersClears the buffers for the specified file and causes all buffered data to be written to the file.
GetBinaryTypeDetermines whether a file is executable.
GetCurrentDirectoryRetrieves the current directory for the current process.
GetDiskFreeSpaceRetrieves information about the specified disk, including the amount of free space on the disk.
GetDiskFreeSpaceExRetrieves information about the specified disk, including the amount of free space on the disk.
GetDriveTypeDetermines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.
GetFileAttributesRetrieves attributes for a specified file or directory.
GetFileAttributesExRetrieves attributes for a specified file or directory.
GetFileInformationByHandleRetrieves file information for a specified file.
GetFileSizeRetrieves the size of a specified file.
GetFileSizeExRetrieves the size of a specified file.
GetFileTypeRetrieves the file type of the specified file.
GetFullPathNameRetrieves the full path and file name of a specified file.
GetLogicalDrivesReturns a bitmask representing the currently available disk drives.
GetLogicalDriveStringsFills a buffer with strings that specify valid drives in the system.
GetLongPathNameConverts the specified path to its long form.
GetQueuedCompletionStatusAttempts to dequeue an I/O completion packet from a specified I/O completion port.
GetShortPathNameRetrieves the short path form of a specified input path.
GetTempFileNameCreates a name for a temporary file.
GetTempPathRetrieves the path of the directory designated for temporary files.
LockFileLocks a region in an open file.
LockFileExLocks a region in an open file for shared or exclusive access.
MoveFileMoves an existing file or a directory.
MoveFileExMoves an existing file or a directory.
MoveFileWithProgressMoves a file or directory.
PostQueuedCompletionStatusPosts an I/O completion packet to an I/O completion port.
QueryDosDeviceRetrieves information about MS-DOS device names.
ReadDirectoryChangesWRetrieves information describing the changes occurring within a directory.
ReadFileReads data from a file, starting at the specified position.
ReadFileExReads data from a file asynchronously.
ReadFileScatterReads data from a file and stores the data into a set of buffers.
RemoveDirectoryDeletes an existing empty directory.
ReplaceFileReplaces one file with another file.
SearchPathSearches for the specified file.
SetCurrentDirectoryChanges the current directory for the current process.
SetEndOfFileMoves the end-of-file position for the specified file.
SetFileApisToANSICauses the file I/O functions to use the ANSI character set code page.
SetFileApisToOEMCauses the file I/O functions to use the OEM character set code page.
SetFileAttributesSets a file‘s attributes.
SetFilePointerMoves the file pointer of an open file.
SetFilePointerExMoves the file pointer of an open file.
SetFileSecuritySets the security of a file or directory object.
SetFileShortNameSets the valid data length of the specified file.
SetFileValidDataSets the valid data length of the specified file.
SetVolumeLabelSets the label of a file system volume.
UnlockFileUnlocks a previously locked region in an open file.
UnlockFileExUnlocks a previously locked region in an open file.
WriteFileWrites data to a file.
WriteFileExWrites data to a file asynchronously.
WriteFileGatherGathers data from a set of buffers and writes the data to a file.
 
    举个创建或打开文件的例子吧,
<span style="font-size:14px;">HANDLE T_FileOpen_Win32(const char *filename, int oflag, int mode)
{
	int ret = 0;
	HANDLE Handle = INVALID_HANDLE_VALUE;
	WCHAR tFileName[WTP_FULL_FILENAME_LEN+1]={0};
	char apiFileName[WTP_FULL_FILENAME_LEN+1]={0};

	strcat(apiFileName,"\\\\\?\\");
	strcat(apiFileName,filename);

	ret = MultiByteToWideChar (CP_ACP, 0, apiFileName, strlen (apiFileName) + 1, tFileName, sizeof(tFileName)/sizeof(tFileName[0])) ; 
	Handle = CreateFileW(tFileName, mode,FILE_SHARE_READ,NULL,oflag,FILE_ATTRIBUTE_NORMAL,NULL);
	ret = GetLastError();

	return Handle;
}</span>
    如何使用呢?
    1)创建或打开文件
         logFileFd = T_FileOpen_Win32(transLogFileFullName,OPEN_ALWAYS,GENERIC_WRITE|GENERIC_READ);
    2)只打开文件
         logFileFd = T_FileOpen_Win32(transLogFileFullName,OPEN_EXISTING,GENERIC_WRITE|GENERIC_READ);

 

    ※喜欢编程开发的朋友,可以加入到“StudyRoad“QQ群(238798556)来交流,认识新朋友,开阔视野,共同提高哦!※