Using CreateFile() and SetFilePointer() Functions
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard and Windows
Additional library: Windows Platform SDK
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info: non-CLR or unmanaged
To do: Playing with file pointer
To show: Using the CreateFile() and SetFilePointer() C functions
#include <windows.h>
#include <stdio.h>
int main(void)
{
// handle for file
HANDLE hFile;
DWORD dwCurrentFilePosition;
// file and path, the file is there
LPCWSTR fname = L"c:\\mytestfile.txt";
hFile = CreateFile(fname, // file to be opened
GENERIC_WRITE, // open for writing
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // open existing file
FILE_ATTRIBUTE_READONLY, //the file is read only
NULL); // no attribute template
if(hFile == INVALID_HANDLE_VALUE)
printf("Could not open %S file, error %d\n", fname, GetLastError());
else
printf("%S file HANDLE is OK!\n", fname);
dwCurrentFilePosition = SetFilePointer(
hFile, // must have GENERIC_READ and/or GENERIC_WRITE
0, // do not move pointer
NULL, // hFile is not large enough in needing this pointer
FILE_CURRENT); // provides offset from current position
printf("Current file pointer position: %d\n", dwCurrentFilePosition);
printf("Moving the file pointer 10 bytes...\n");
dwCurrentFilePosition = SetFilePointer(
hFile, // must have GENERIC_READ and/or GENERIC_WRITE
10, // 10 bytes
NULL, // hFile is not large enough to need this pointer
FILE_CURRENT); //provides offset from current position
printf("Current file pointer position: %d\n", dwCurrentFilePosition);
// close the file's handle and itself
if(CloseHandle(hFile) == 0)
printf("%S file handle can't be closed! Error code: %d\n", fname, GetLastError());
else
printf("%S file handle closed successfully\n", fname);
return 0;
// return 0;
}
Output example:
c:\mytestfile.txt file HANDLE is OK!
Current file pointer position: 0
Moving the file pointer 10 bytes...
Current file pointer position: 10
c:\mytestfile.txt file handle closed successfully
Press any key to continue . . .