Your browser doesn't support JavaScript File Management API Functions - Windows Programming

File Management API Functions

The Win32 API offers a set of functions for accessing and managing disk files. This is in addition to the I/O functions available as part of the C and C++ runtime libraries. A selection of these API functions is outlined below.

For further reading on the full list of file management functions 

https://docs.microsoft.com/en-us/windows/win32/fileio/file-management-functions

Creating and Opening Files

All types of files can be created and opened with the API function CreateFile(). Windows assigns a file handle to each file that is opened or created. This handle is then used to access that file. File handles are valid until closed with the CloseHandle() function, which closes the file and flushes the buffers. The prototype of this function is

HANDLE CreateFile(LPCSTR lpFileName,DWORD dwAccess,DWORD dwShareMode,LPSECURITY_ATTRIBUTES lpSecurityAttributes,DWORD dwCreationDisposition,DWORD dwFlagsAndAttributes,HANDLE hTemplateFile);

Where
lpFileName – The name of the file or device to be created or opened with a backslash (\) to separate the components of a path.
dwAccess – The requested access to the file or device, which can be summarized as read, write, both or neither
dwShareMode – read, write, both, delete, all of these, or none.
lpSecurityAttributes – determines whether the child processes can be inherited the returned handle. This parameter can be NULL.
dwCreationDisposition – An action to take on a file or device that exists or does not exist.
dwFlagsAndAttributes – file or device attributes and flag
hTemplateFile – handle to a template file that supplies file attributes and extended attributes for the file that is being created. This parameter can be NULL.

If the function succeeds, the return value is an open handle to the specified file. If the function fails, the return value is INVALID_HANDLE_VALUE

Reading From and Writing to a File

When a file is first opened, Windows places a file pointer at the start of the file. Windows then advances the file pointer after the next read or write operation. An application can also move the file pointer position with the SetFilePointer() function. An application performs read and write operations with the ReadFile() and WriteFile() API functions. The prototype of these functions are –

BOOL ReadFile(HANDLE hFile,LPVOID lpBuffer,DWORD nNumberOfBytes,LPDWORD lpNumberOfBytes,LPOVERLAPPED lpOverlapped);

BOOL WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytes, LPDWORD lpNumberOfBytes, LPOVERLAPPED lpOverlapped );

Where
hFile – A handle to the device
lpBuffer – A pointer to the buffer that holds the data to be read or written.
nNumberOfBytes – The maximum number of bytes to be read or written.
lpNumberOfBytes – Number of bytes read or written when using a synchronous hFile parameter. 
lpOverlapped – A pointer to an OVERLAPPED structure.

If the function succeeds, the return value is nonzero.  If the function fails the return value is zero.

When the file pointer reaches the end of the file any attempts to read any further data will return an error.

Windows allows more than one application to open a file and write to it. To prevent two applications from trying to write to the same file simultaneously, an application can lock the shared file area with the LockFile() function (see below). Locking part of a file prevents other processes from reading or writing anywhere in the specified area. When the application has completed its file operations it can unlock that region of the file using the UnlockFile() function. All locked regions of a file should be unlocked before closing a file.

The code section below demonstrates the API functions ReadFile() and WriteFile() by creating and then writing to a simple text file and then reading the contents before displaying them in a messagebox

#include <windows.h>
int APIENTRY WinMain( HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow )
{
 HANDLE hFile;
// create the file.
hFile = CreateFile( TEXT("FILE1.TXT"), GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ, NULL, OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL, NULL );
if ( hFile != INVALID_HANDLE_VALUE )
{
DWORD dwByteCount;
TCHAR szBuf[64]=TEXT("/0");
// Write a simple string to hfile.
WriteFile( hFile, "This is a simple message", 25, &dwByteCount, NULL );
// Set the file pointer back to the beginning of the file.
SetFilePointer( hFile, 0, 0, FILE_BEGIN );
// Read the string back from the file.
ReadFile( hFile, szBuf, 128, &dwByteCount, NULL );
// Null terminate the string.
szBuf[dwByteCount] = 0;
// Close the file.
CloseHandle( hFile );
//output message with string if successful
 MessageBox( NULL, TEXT("File created"), TEXT(""), MB_OK );
}
else
{
//output message if unsuccessful
 MessageBox( NULL, TEXT("File not created"), TEXT(""), MB_OK );
}
 return 0;
}

CopyFile

Copies an existing file to a new file but not the security attributes. The prototype of the copyfile() API function is

BOOL CopyFile(LPCTSTR lpExistingFileName,LPCTSTR lpNewFileName,BOOL bFailIfExists);

Where
lpExistingFileName – The name of an existing file.
lpNewFileName – The name of the new file.
bFailIfExists – If this parameter is TRUE and the new file already exists the function fails. If this parameter is FALSE and the new file already exists, the function overwrites the existing file and returns true.

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.

CreateDirectory

Creates a new directory. The function applies a specified security descriptor to the new directory if the underlying file system is NTFS or one that supports security on files and directories. The prototype of this function is

BOOL CreateDirectory(LPCSTR lpPathName,LPSECURITY_ATTRIBUTES lpSecurityAttributes);

lpPathName – The path of the directory to be created
lpSecurityAttributes – A pointer to a SECURITY_ATTRIBUTES structure

Returns TRUE if successful; otherwise, the return value is FALSE.

DeleteFile

Deletes an existing file. If an application attempts to delete an open file or a file that does not exist, the function fails. The prototype of this function is

BOOL DeleteFile(LPCSTR lpFileName);

Where LpFileName is the name of the file to be deleted.  If the function succeeds, the return value is nonzero. If the function fails, the return value is zero (0).

GetFileAttributes

Retrieves file system attributes for a specified file or directory. The prototype of this function is

DWORD GetFileAttributes(LPCSTR lpFileName);

Where lpFileName is the name of the file or directory.  If the function succeeds, the return value contains the attributes of the specified file or directory. If the function fails, the return value is INVALID_FILE_ATTRIBUTES.

MoveFile

Moves an existing file or a directory to a new location on a volume. MoveFile will fail on directory moves when the destination is on a different volume. The prototype for this function is

BOOL MoveFile(LPCTSTR lpExistingFileName,LPCTSTR lpNewFileName);

LpExistingFileName – The name of the file or directory on the local computer.
LpNewFileName – The new name for the file or directory.

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.

RemoveDirectory.

Deletes the specified empty directory. The prototype of this function is

BOOL RemoveDirectory( LPCTSTR lpszDir );

Where lpszDir is a pointer to a null-terminated string that contains the path of the directory to be removed. The directory must be empty and the calling process must have delete access to the directory.  Returns true if successful; otherwise, the return value is FALSE. 

LockFile

Locks a region in an open file. The prototype for this function is

BOOL LockFile(HANDLE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh);

where
hFile – A handle to the file.
dwFileOffsetLow – The low-order 32 bits of the starting byte offset in the file where the lock should begin.
dwFileOffsetHigh – The high-order 32 bits of the starting byte offset in the file where the lock should begin.
nNumberOfBytesToLockLow– The low-order 32 bits of the length of the byte range to be locked.
nNumberOfBytesToLockHigh -The high-order 32 bits of the length of the byte range to be locked.

If the function succeeds, the return value is nonzero (TRUE). If the function fails, the return value is zero (FALSE). 

UnlockFile

Unlocks a region in an open file

BOOL UnlockFile(HANDLE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,DWORD nNumberOfBytesToUnlockLow,DWORD nNumberOfBytesToUnlockHigh);

where
hFile – A handle to the file that contains a region locked with LockFile.
dwFileOffsetLow – The low-order word of the starting byte offset in the file where the locked region begins.
dwFileOffsetHigh – The high-order word of the starting byte offset in the file where the locked region begins.
nNumberOfBytesToUnlockLow – The low-order word of the length of the byte range to be unlocked.
nNumberOfBytesToUnlockHigh – The high-order word of the length of the byte range to be unlocked.

If the function succeeds, the return value is nonzero. – If the function fails, the return value is zero.