Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

SetFilePointer function (fileapi.h)

  • 2022-07-27
Feedback

In this article

Moves the file pointer of the specified file.

This function stores the file pointer in twoLONG values. To work with file pointersthat are larger than a singleLONG value, it is easier to use theSetFilePointerEx function.

Syntax

DWORD SetFilePointer(  [in]                HANDLE hFile,  [in]                LONG   lDistanceToMove,  [in, out, optional] PLONG  lpDistanceToMoveHigh,  [in]                DWORD  dwMoveMethod);

Parameters

[in] hFile

A handle to the file.

The file handle must be created with theGENERIC_READ orGENERIC_WRITE access right. For more information, seeFile Security and Access Rights.

[in] lDistanceToMove

The low order 32-bits of a signed value that specifies the number of bytes to move the file pointer.

IflpDistanceToMoveHigh is notNULL,lpDistanceToMoveHigh andlDistanceToMove form a single64-bit signed value that specifies the distance to move.

IflpDistanceToMoveHigh isNULL,lDistanceToMove is a 32-bit signed value. A positive value forlDistanceToMove moves the file pointer forward in the file, and a negative valuemoves the file pointer back.

[in, out, optional] lpDistanceToMoveHigh

A pointer to the high order 32-bits of the signed 64-bit distance to move.

If you do not need the high order 32-bits, this pointer must be set toNULL.

When notNULL, this parameter also receives the high orderDWORD of the new value of the file pointer. For more information, see the Remarkssection in this topic.

[in] dwMoveMethod

The starting point for the file pointer move.

This parameter can be one of the following values.

ValueMeaning
FILE_BEGIN
0
The starting point is zero or the beginning of the file.
FILE_CURRENT
1
The starting point is the current value of the file pointer.
FILE_END
2
The starting point is the current end-of-file position.

Return value

If the function succeeds andlpDistanceToMoveHigh isNULL, the return value is the low-orderDWORD of the newfile pointer.Note  If the function returns a value other thanINVALID_SET_FILE_POINTER, the calltoSetFilePointer has succeeded. You do not need tocallGetLastError.

If function succeeds andlpDistanceToMoveHigh is notNULL, the return value is the low-orderDWORD of the newfile pointer andlpDistanceToMoveHigh contains the high orderDWORD of the new file pointer.

If the function fails, the return value isINVALID_SET_FILE_POINTER. To getextended error information, callGetLastError.

If a new file pointer is a negative value, the function fails, the file pointer is not moved, and the codereturned byGetLastError isERROR_NEGATIVE_SEEK.

IflpDistanceToMoveHigh isNULL and the new file positiondoes not fit in a 32-bit value, the function fails and returnsINVALID_SET_FILE_POINTER.

Note  BecauseINVALID_SET_FILE_POINTER is a valid value for the low-orderDWORD of the new file pointer, you must check both the return value of the function and the error code returned byGetLastError to determine whether or not an error has occurred. If an error has occurred, the return value ofSetFilePointer isINVALID_SET_FILE_POINTER andGetLastError returns a value other thanNO_ERROR. For a code example that demonstrates how to check for failure, see the Remarks section in this topic.
 

Remarks

The file pointer that is identified by the value of thehFile parameter is not usedfor overlapped read and write operations.

ThehFile parameter must refer to a file stored on a seeking device; for example, a disk volume. Calling theSetFilePointer function with a handle to a non-seekingdevice such as a pipe or a communications device is not supported, even though theSetFilePointer function may not return an error. The behavior of theSetFilePointer function in this case is undefined.

To specify the offset for overlapped operations

  • Use theOffset andOffsetHigh members of theOVERLAPPED structure.

To determine the file type forhFile

For information about how to determine the position of a file pointer, seePositioning a File Pointer.

Be careful when you set a file pointer in a multithreaded application. You must synchronize access to sharedresources. For example, an application with threads that share a file handle, update the file pointer, and readfrom the file must protect this sequence by using a critical section object or mutex object. For more information,seeCritical Section Objects andMutex Objects.

If thehFile handle is opened with theFILE_FLAG_NO_BUFFERING flag set, an application can move the file pointer only tosector-aligned positions. A sector-aligned position is a position that is a whole number multiple of the volumesector size. An application can obtain a volume sector size by calling theGetDiskFreeSpace function.

If an application callsSetFilePointer with distanceto move values that result in a position not sector-aligned and a handle that is opened withFILE_FLAG_NO_BUFFERING, the function fails, andGetLastError returnsERROR_INVALID_PARAMETER.

It is not an error to set a file pointer to a position beyond the end of the file. The size of the file doesnot increase until you call theSetEndOfFile,WriteFile, orWriteFileEx function. A write operation increases the sizeof the file to the file pointer position plus the size of the buffer written, which results in the interveningbytes being zero initialized.

If the return value isINVALID_SET_FILE_POINTER and iflpDistanceToMoveHigh is non-NULL, an application must callGetLastError to determine whether or not the function hassucceeded or failed. The following code example shows you that scenario.

  // Case One: calling the function with lpDistanceToMoveHigh == NULL   // Try to move hFile file pointer some distance    DWORD dwPtr = SetFilePointer( hFile,                                 lDistance,                                 NULL,                                 FILE_BEGIN );      if (dwPtr == INVALID_SET_FILE_POINTER) // Test for failure   {     // Obtain the error code.     DWORD dwError = GetLastError() ;        // Deal with failure     // . . .       } // End of error handler   //  // Case Two: calling the function with lpDistanceToMoveHigh != NULL  // Try to move hFile file pointer a huge distance   DWORD dwPtrLow = SetFilePointer( hFile,                                    lDistLow,                                    &lDistHigh,                                    FILE_BEGIN );      // Test for failure  if ( dwPtrLow == INVALID_SET_FILE_POINTER &&        GetLastError() != NO_ERROR )   {    // Deal with failure    // . . .   } // End of error handler

Although the parameterlpDistanceToMoveHigh is used to manipulate huge files, thevalue of the parameter should be set when moving files of any size. If it is set toNULL, thenlDistanceToMove has a maximum value of2^31–2, or 2 gigabytes less 2, because all file pointer values are signed values. Therefore,if there is even a small chance for the file to increase to that size, it is best to treat the file as a huge fileand work with 64-bit file pointers. Withfile compression on the NTFS filesystem, andsparse files, it is possible to have files thatare large even if the underlying volume is not very large.

IflpDistanceToMoveHigh is notNULL, thenlpDistanceToMoveHigh andlDistanceToMove form a single 64-bitsigned value. ThelDistanceToMove parameter is treated as the low-order 32 bits of thevalue, andlpDistanceToMoveHigh as the high-order 32 bits, which means thatlpDistanceToMoveHigh is a sign extension oflDistanceToMove.

To move the file pointer from zero to 2 gigabytes,lpDistanceToMoveHigh must beset to eitherNULL or a sign extension oflDistanceToMove. Tomove the pointer more than 2 gigabytes, uselpDistanceToMoveHigh andlDistanceToMove as a single 64-bit quantity. For example, to move in the range from 2gigabytes to 4 gigabytes set the contents oflpDistanceToMoveHigh to zero, or to–1 for a negative sign extension oflDistanceToMove.

To work with 64-bit file pointers, you can declare aLONG, treat it as the upperhalf of the 64-bit file pointer, and pass its address inlpDistanceToMoveHigh. Thismeans that you have to treat two different variables as a logical unit, which can cause an error. It is best touse theLARGE_INTEGER structure to create a 64-bit value and pass the two 32-bitvalues by using the appropriate elements of the union.

Also, it is best to use a function to hide the interface toSetFilePointer. The following code example shows you thatscenario.

__int64 myFileSeek (HANDLE hf, __int64 distance, DWORD MoveMethod){   LARGE_INTEGER li;   li.QuadPart = distance;   li.LowPart = SetFilePointer (hf,                                 li.LowPart,                                 &li.HighPart,                                 MoveMethod);   if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError()        != NO_ERROR)   {      li.QuadPart = -1;   }   return li.QuadPart;}

You can useSetFilePointer to determine the length ofa file. To do this, useFILE_END fordwMoveMethod and seek tolocation zero. The file offset returned is the length of the file. However, this practice can have unintendedside effects, for example, failure to save the current file pointer so that the program can return to thatlocation. It is best to useGetFileSize instead.

You can also use theSetFilePointer function to querythe current file pointer position. To do this, specify a move method ofFILE_CURRENT anda distance of zero.

In Windows 8 and Windows Server 2012, this function is supported by the following technologies.

TechnologySupported
Server Message Block (SMB) 3.0 protocolYes
SMB 3.0 Transparent Failover (TFO)Yes
SMB 3.0 with Scale-out File Shares (SO)Yes
Cluster Shared Volume File System (CsvFS)Yes
Resilient File System (ReFS)Yes
 

Examples

For a code example of appending files, seeAppending One File to Another File.

Requirements

RequirementValue
Minimum supported clientWindows XP [desktop apps | UWP apps]
Minimum supported serverWindows Server 2003 [desktop apps | UWP apps]
Target PlatformWindows
Headerfileapi.h (include Windows.h)
LibraryKernel32.lib
DLLKernel32.dll

See also

File Management Functions

GetDiskFreeSpace

GetFileSize

GetFileType

ReadFile

ReadFileEx

SetEndOfFile

SetFilePointerEx

WriteFile

WriteFileEx


Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo