Windows File Open: What It Means in Win32
In this article
In Win32, "file open" means the process of establishing a handle to a file or device through the CreateFile function, which grants the caller a set of requested access rights (read, write, or both) and returns a handle used for subsequent operations. This handle is the key to all file I/O in the Windows API, and understanding it is essential for debugging file-sharing errors, writing robust applications, and managing system resources.
Background: The Win32 File Model
Win32 is the primary API for 32-bit and 64-bit Windows applications. It treats files as linear byte streams, unlike some other operating systems that impose record structures. The central object is the file handle, an opaque value that the kernel uses to identify an open file instance. Handles are also used for other kernel objects (processes, events, mutexes), but file handles are the most common.
The CreateFile function is the universal entry point. Despite its name, it opens existing files, creates new ones, opens directories, and even opens devices like serial ports or named pipes. The function signature is:
HANDLE CreateFile( LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile);Each parameter controls a different aspect of the open operation, and together they determine what you can do with the file and how other processes can access it concurrently.
How File Open Works
When a process calls CreateFile, the kernel performs a series of steps:
- Name resolution: The file path is parsed, and the appropriate file system driver (NTFS, FAT, exFAT, etc.) is identified.
- Security check: The system verifies that the caller has the right to access the file with the requested access rights, based on the file's security descriptor and the caller's token.
- Share mode check: The system checks the sharing flags of the file against the share modes of any existing open handles. If a conflict exists, the open fails with
ERROR_SHARING_VIOLATION(32). - Creation disposition: Depending on the value (e.g.,
CREATE_NEW,OPEN_EXISTING,CREATE_ALWAYS), the system either creates a new file, opens an existing one, or truncates it. - Handle creation: If all checks pass, the kernel creates a handle and associates it with the file object in the system's object manager.
The handle is then used with functions like ReadFile, WriteFile, SetFilePointer, and CloseHandle. The handle also tracks the current file position, which is advanced by reads and writes.
Choosing Parameters Correctly
Selecting the right parameters is crucial for avoiding errors and ensuring your application works as intended.
- Desired access: Use
GENERIC_READfor reading,GENERIC_WRITEfor writing, or both. Requesting write access when you only need to read can cause sharing violations if another process already has the file open for writing. - Share mode: This controls what other processes can do while you have the file open. Common values are
FILE_SHARE_READ(others can read),FILE_SHARE_WRITE(others can write), or both. If you set 0, you deny all sharing; this is often used for exclusive access but can cause problems for other applications. - Creation disposition: For opening an existing file, use
OPEN_EXISTING. For creating a new file, useCREATE_NEW(fails if it exists) orCREATE_ALWAYS(overwrites).OPEN_ALWAYSopens or creates if missing. - Flags and attributes: Use
FILE_ATTRIBUTE_NORMALfor typical files. For sequential access, useFILE_FLAG_SEQUENTIAL_SCANto optimize caching. For random access,FILE_FLAG_RANDOM_ACCESS.
In practice, many developers use the C runtime functions like fopen or the .NET File.Open, which wrap CreateFile and provide sensible defaults. However, when you need fine control (e.g., opening a file for overlapped I/O), you must use the Win32 API directly.
Common Problems and Misconceptions
One frequent error is ERROR_SHARING_VIOLATION, which occurs when a file is already open with a share mode that conflicts with your request. For example, if another process has the file open with no sharing (dwShareMode=0), any subsequent open will fail. This often happens when an antivirus scanner or a file indexer briefly opens a file, causing your application to fail. The typical fix is to retry the open after a short delay or to use a more permissive share mode when you first open the file.
Another misconception is that CreateFile with CREATE_ALWAYS will fail if the file is read-only. In fact, it will fail with ERROR_ACCESS_DENIED because the system cannot truncate a read-only file. Similarly, opening a directory requires the FILE_FLAG_BACKUP_SEMANTICS flag; otherwise, the open fails.
Many developers also confuse the file handle with the file itself. The handle is per-process and per-open; two handles to the same file have independent file pointers. Closing one handle does not affect the other, but the file is not deleted until all handles are closed (if you requested delete-on-close).
File Open vs. File Locking
File open and file locking are related but distinct concepts. Opening a file with a share mode of 0 is a form of locking: it prevents other processes from opening the file at all. However, you can also lock byte ranges within a file using LockFile or LockFileEx. These locks are advisory in the sense that they are only enforced when other processes attempt to lock the same range; they do not prevent reads or writes. Range locks are useful for coordinating access to specific parts of a large file, such as a database.
The share mode is the primary mechanism for preventing conflicts. A process that opens a file for writing should typically allow FILE_SHARE_READ so that other processes can read the file while it is being written, but deny FILE_SHARE_WRITE to prevent concurrent writes. This is the default behavior in many high-level APIs.
Alternatives to CreateFile
For most applications, you do not need to call CreateFile directly. High-level alternatives include:
- C runtime (
fopen,_open): These provide buffered I/O and are portable to other operating systems. - C++ standard library (
std::ifstream,std::ofstream): These are type-safe and RAII-based, automatically closing the file when the object goes out of scope. - .NET (
File.Open,FileStream): These offer a managed wrapper with garbage-collected handles. - WinRT (
StorageFile): For UWP apps, this is the modern API.
Each of these eventually calls CreateFile (or CreateFile2 on newer systems), but they handle the details of parameter selection and error handling for you. Use the low-level API only when you need specific features like overlapped I/O, file change notifications, or access to named pipes.
Frequently Asked Questions
Why do I get a sharing violation when opening a file?
A sharing violation (error 32) occurs when the file is already open with a share mode that does not allow your requested access. For example, if another process opened the file without FILE_SHARE_READ, your attempt to open it for reading will fail. Check your own share modes and consider using a more permissive mode, or retry after a short delay.
What is the difference between CreateFile and OpenFile?
OpenFile is an older, deprecated function that is kept for compatibility with 16-bit Windows. It does not support all the features of CreateFile, such as security attributes, overlapped I/O, or opening devices. Always use CreateFile (or CreateFile2) for new code.
Can I open a file for both reading and writing at the same time?
Yes, request GENERIC_READ | GENERIC_WRITE as the desired access. You can then use ReadFile and WriteFile on the same handle. Be aware that the file pointer is shared, so you may need to call SetFilePointer between operations.
What does FILE_SHARE_DELETE do?
It allows other processes to delete the file while you have it open. This is useful for temporary files or log files that may be rotated. Without this flag, a delete attempt will fail with a sharing violation. Note that the file is not actually removed until all handles are closed.
Why does my program fail to open a file that exists?
There are several possible reasons: the file may be locked by another process, the path may be incorrect, the process may not have permission to access the file (e.g., due to ACLs), or the file may be a directory. Use the GetLastError function to get the specific error code and refer to the system error codes documentation.
Is it safe to use CREATE_ALWAYS to overwrite a file?
Yes, but only if you are sure you want to overwrite it. CREATE_ALWAYS truncates the file if it exists. If you want to avoid accidental data loss, use CREATE_NEW to fail if the file exists, or check for existence first with GetFileAttributes.