The DeleteFile function deletes an existing file.
To compile an application that uses this function, the C runtime library (CRT) is not required.
BOOL DeleteFileA(
LPCSTR lpFileName
);
The DeleteFile function deletes an existing file.
To compile an application that uses this function, the C runtime library (CRT) is not required.
| Type | Name | Description |
|---|---|---|
LPCSTR |
lpFileName |
A null-terminated string that specifies 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. To get extended error information, call GetLastError.
If the specified file is a read-only file, a file with a hidden attribute, or a directory, the function fails and returns FALSE. If the file is a hidden file, the function fails and returns FALSE. To delete a read-only file, you must first remove the read-only attribute.
The DeleteFile function can be used to delete files on a local computer or on a remote computer. If the file is on another computer, the lpFileName parameter must specify the full path of the file on the remote computer.
If the calling process or any other process has an open handle to the file, the file is deleted, but it remains accessible until the last handle is closed. The file is then removed from the file system.
To delete a directory, use the RemoveDirectory function.
For a more generalized file deletion function, consider using the SHFileOperation function.
The following example deletes a file named "MyFile.txt" in the current directory.
#include <windows.h>
int main() {
if (DeleteFileA("MyFile.txt")) {
MessageBoxA(NULL, "File deleted successfully!", "Success", MB_OK);
} else {
DWORD error = GetLastError();
char buffer[256];
sprintf_s(buffer, sizeof(buffer), "Failed to delete file. Error code: %lu", error);
MessageBoxA(NULL, buffer, "Error", MB_OK | MB_ICONERROR);
}
return 0;
}