Win32 File API CopyFile function

Download EaseFilter Monitor, Control and Encryption Filter Driver SDK Setup File
Download EaseFilter Monitor, Control and Encryption Filter Driver SDK Zip File

Copies an existing file to a new file.

The CopyFileEx function provides two additional capabilities. CopyFileEx can call a specified callback function each time a portion of the copy operation is completed, and CopyFileEx can be canceled during the copy operation.

To perform this operation as a transacted operation, use the CopyFileTransacted function.

Syntax

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

Parameters

lpExistingFileName

The name of an existing file.

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. For more information, see Naming a File.

Tip  Starting with Windows 10, version 1607, for the unicode version of this function (CopyFileW), you can opt-in to remove the MAX_PATH limitation without prepending "\\?\". See the "Maximum Path Length Limitation" section of Naming Files, Paths, and Namespaces for details.
 
If lpExistingFileName does not exist, CopyFile fails, and GetLastError returns ERROR_FILE_NOT_FOUND.

lpNewFileName

The name of the new file.

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. For more information, see Naming a File.

Tip  Starting with Windows 10, version 1607, for the unicode version of this function (CopyFileW), you can opt-in to remove the MAX_PATH limitation without prepending "\\?\". See the "Maximum Path Length Limitation" section of Naming Files, Paths, and Namespaces for details.
 

bFailIfExists

If this parameter is TRUE and the new file specified by lpNewFileName already exists, the function fails. If this parameter is FALSE and the new file already exists, the function overwrites the existing file and succeeds.

Return Value

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.

Remarks

The security resource properties (ATTRIBUTE_SECURITY_INFORMATION) for the existing file are copied to the new file.

Windows 7, Windows Server 2008 R2, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:  Security resource properties for the existing file are not copied to the new file until Windows 8 and Windows Server 2012.

File attributes for the existing file are copied to the new file. For example, if an existing file has the FILE_ATTRIBUTE_READONLY file attribute, a copy created through a call to CopyFile will also have the FILE_ATTRIBUTE_READONLY file attribute.

This function fails with ERROR_ACCESS_DENIED if the destination file already exists and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_READONLY attribute set.

When CopyFile is used to copy an encrypted file, it attempts to encrypt the destination file with the keys used in the encryption of the source file. If this cannot be done, this function attempts to encrypt the destination file with default keys. If neither of these methods can be done, CopyFile fails with an ERROR_ENCRYPTION_FAILED error code.

Symbolic link behavior—If the source file is a symbolic link, the actual file copied is the target of the symbolic link.

If the destination file already exists and is a symbolic link, the target of the symbolic link is overwritten by the source file.

Example

An application can retrieve the file attributes by using the GetFileAttributes or GetFileAttributesEx function. The CreateFile and SetFileAttributes functions can set many of the attributes. However, applications cannot set all attributes.

The code example in this topic uses the CopyFile function to copy all text files (.txt) in the current directory to a new directory of read-only files. Files in the new directory are changed to read only, if necessary.

The application creates the directory specified as a parameter by using the CreateDirectory function. The directory must not exist already.

The application searches the current directory for all text files by using the FindFirstFile and FindNextFile functions. Each text file is copied to the \TextRO directory. After a file is copied, the GetFileAttributes function determines whether or not a file is read only. If the file is not read only, the application changes directories to \TextRO and converts the copied file to read only by using the SetFileAttributes function.

After all text files in the current directory are copied, the application closes the search handle by using the FindClose function.

#include <windows.h>  
#include <tchar.h>  
#include <stdio.h>  
#include <strsafe.h>    

void _tmain(int argc, TCHAR* argv[])  
{     
	WIN32_FIND_DATA FileData;     
	HANDLE          hSearch;     
	DWORD           dwAttrs;     
	TCHAR           szNewPath[MAX_PATH];           
	BOOL            fFinished = FALSE;       

	if(argc != 2)     
	{       
		_tprintf(TEXT("Usage: %s <dir>\n"), argv[0]);        
		return;    
	}     

	// Create a new directory.         

	if (!CreateDirectory(argv[1], NULL))      
	{         
		printf("CreateDirectory failed (%d)\n", GetLastError());         
		return;     
	}      

	// Start searching for text files in the current directory.         

	hSearch = FindFirstFile(TEXT("*.txt"), &FileData);      
	if (hSearch == INVALID_HANDLE_VALUE)      
	{         
		printf("No text files found.\n");         
		return;     
	}      

	// Copy each .TXT file to the new directory   
	// and change it to read only, if not already.         

	while (!fFinished)      
	{         
		StringCchPrintf(szNewPath, sizeof(szNewPath)/sizeof(szNewPath[0]), TEXT("%s\\%s"), argv[1], FileData.cFileName);          

		if (CopyFile(FileData.cFileName, szNewPath, FALSE))        
		{            
			dwAttrs = GetFileAttributes(FileData.cFileName);            
			if (dwAttrs==INVALID_FILE_ATTRIBUTES) 
				return;              

			if (!(dwAttrs & FILE_ATTRIBUTE_READONLY))            
			{               
				SetFileAttributes(szNewPath,                   
					dwAttrs | FILE_ATTRIBUTE_READONLY);            
			}         
		}        
		else         
		{            
			printf("Could not copy file.\n");            
			return;        
		}            

		if (!FindNextFile(hSearch, &FileData))         
		{           
			if (GetLastError() == ERROR_NO_MORE_FILES)            
			{               
				_tprintf(TEXT("Copied *.txt to %s\n"), argv[1]);               
				fFinished = TRUE;           
			}            
			else            
			{               
				printf("Could not find next file.\n");               
				return;           
			}         
		}     
	}      
	// Close the search handle.         

	FindClose(hSearch);  
}