The Windows Disk Management 14

 

 

 

 

 

DeleteFile() Function

 

Deletes an existing file. To perform this operation as a transacted operation, use the DeleteFileTransacted() function. The syntax is:

 

BOOL WINAPI DeleteFile(LPCTSTR lpFileName);

 

Parameters

 

lpFileName [in] - The name of the file to be deleted. In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.

 

Return Value

 

If the function succeeds, the return value is nonzero and if the function fails, the return value is zero (0). To get extended error information, call GetLastError().

If an application attempts to delete a file that does not exist, the DeleteFile() function fails with ERROR_FILE_NOT_FOUND. If the file is a read-only file, the function fails with ERROR_ACCESS_DENIED. The following list identifies some tips for deleting, removing, or closing files:

 

  1. To delete a read-only file, first you must remove the read-only attribute.
  2. To delete or rename a file, you must have either delete permission on the file, or delete child permission in the parent directory.
  3. To recursively delete the files in a directory, use the SHFileOperation() function.
  4. To remove an empty directory, use the RemoveDirectory() function.
  5. To close an open file, use the CloseHandle() function.

 

If you set up a directory with all access except delete and delete child, and the access control lists (ACL) of new files are inherited, then you can create a file without being able to delete it. However, then you can create a file, and then get all the access you request on the handle that is returned to you at the time you create the file. If you request delete permission at the time you create a file, you can delete or rename the file with that handle, but not with any other handle. The DeleteFile() function fails if an application attempts to delete a file that is open for normal I/O or as a memory-mapped file. The DeleteFile() function marks a file for deletion on close. Therefore, the file deletion does not occur until the last handle to the file is closed. Subsequent calls to CreateFile() to open the file fail with ERROR_ACCESS_DENIED.

 

Symbolic link behavior

 

If the path points to a symbolic link, the symbolic link is deleted, not the target. To delete a target, you must call CreateFile() and specify FILE_FLAG_DELETE_ON_CLOSE.

 

Deleting a File Program Example

 

Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.

 

Deleting a File Program Example: Creating new Win32 C++ console application project in Visual C++ .NET

 

Then, add the source file and give it a suitable name.

Next, add the following source code.

 

#include <windows.h>

#include <stdio.h>

#include <stdlib.h>

 

#define NUMWRITES 10

#define TESTSTRLEN 11

 

const char TestData[NUMWRITES][TESTSTRLEN] =

{

    "TestData0\n",

    "TestData1\n",

    "TestData2\n",

    "TestData3\n",

    "TestData4\n",

    "TestData5\n",

    "TestData6\n",

    "TestData7\n",

    "TestData8\n",

    "TestData9\n"

};

 

int main(int argc, char *argv[])

{

    BOOL fSuccess = FALSE;

 

    // Create the file, open for both read and write.

    HANDLE hFile = CreateFile(TEXT("datafile.txt"),

                       GENERIC_READ | GENERIC_WRITE,

                       0,          // open with exclusive access

                       NULL,       // no security attributes

                       CREATE_NEW, // creating a new temp file

                       0,          // not overlapped index/O

                       NULL);

   

    if (hFile == INVALID_HANDLE_VALUE)

    {

        // Handle the error.

        printf("CreateFile() failed, error %d\n", GetLastError());

        return (1);

    }

 

      printf("CreateFile() is OK!\n");

 

    // Write some data to the file.

    DWORD dwNumBytesWritten = 0;

 

    for (int i=0; i<NUMWRITES; i++)

    {

        fSuccess = WriteFile(hFile,

                             TestData[i],

                             TESTSTRLEN,

                             &dwNumBytesWritten,

                             NULL);  // sync operation.

        if (!fSuccess)

        {

           // Handle the error.

           printf("WriteFile() failed, error %d\n", GetLastError());

           return (2);

        }

            else

                  printf("WriteFile() is OK!\n");

    }

 

    FlushFileBuffers(hFile);

 

    // Lock the 4th write-section. 

    // First, set up the Overlapped structure with the file offset required by LockFileEx(), three lines in to the file.

    OVERLAPPED sOverlapped;

    sOverlapped.Offset = TESTSTRLEN * 3;

    sOverlapped.OffsetHigh = 0;

 

    // Actually lock the file.  Specify exclusive access, and fail

    // immediately if the lock cannot be obtained.

    fSuccess = LockFileEx(hFile,         // exclusive access,

                          LOCKFILE_EXCLUSIVE_LOCK |

                          LOCKFILE_FAIL_IMMEDIATELY,

                          0,             // reserved, must be zero

                          TESTSTRLEN,    // number of bytes to lock

                          0,

                          &sOverlapped); // contains the file offset

    if (!fSuccess)

    {

       // Handle the error.

       printf ("LockFileEx() failed, error %d\n", GetLastError());

       return (3);

    }

    else printf("LockFileEx() succeeded\n");

 

    /////////////////////////////////////////////////////////////////

    // Add code that does something interesting to locked section,  /

    // which should be line 4

    /////////////////////////////////////////////////////////////////

 

    // Unlock the file.

    fSuccess = UnlockFileEx(hFile,

                            0,             // reserved, must be zero

                            TESTSTRLEN,    // num. of bytes to unlock

                            0,

                            &sOverlapped); // contains the file offset

    if (!fSuccess)

    {

       // Handle the error.

       printf ("UnlockFileEx() failed, error %d\n", GetLastError());

       return (4);

    }

    else printf("UnlockFileEx() succeeded\n");

 

    // Clean up handles, memory, and the created file.

    fSuccess = CloseHandle(hFile);

    if (!fSuccess)

    {

       // Handle the error.

       printf ("CloseHandle failed, error %d\n", GetLastError());

       return (5);

    }

 

    fSuccess = DeleteFile(TEXT("datafile.txt"));

    if (!fSuccess)

    {

        // Handle the error.

       printf ("DeleteFile() failed, error %d\n", GetLastError());

       return (6);

    }

      else

            printf ("DeleteFile() is  OK!\n");

    return (0);

}

 

Build and run the project. The following screenshot is a sample output.

 

Deleting a File Program Example: A sample console program output in action

 

The Unicode version can be found in the download page.

 

 

 

 

< Windows Disk 13 | Win32 Programming Index Page | Windows Disk Index | Windows Disk 15 >