FindFirstFile(), lstrcpy(), lstrcat(), SetFileAttributes(), CopyFile(), FindClose()



Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard and Windows

Additional library: Windows Platform SDK

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: non-CLR or unmanaged

To do: Finding a file and various file management

To show: Using FindFirstFile(), lstrcpy(), lstrcat(), SetFileAttributes(), CopyFile(), FindClose() C functions





#include <windows.h>

#include <stdio.h>


int main(void)



HANDLE hSearch;

DWORD dwAttrs;


//LPCWSTR szDirPath = L"E:\\newdir\\";

//LPWSTR szNewPath = malloc(sizeof(MAX_PATH));

TCHAR szDirPath[] = TEXT("E:\\newdir\\");



BOOL fFinished = FALSE;


//Create a new directory. If something wrong

if(!CreateDirectory(szDirPath, NULL))


printf("Could not create %S directory.\n", szDirPath);

//just exit

exit (0);



printf("%S directory successfully created.\n", szDirPath);


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

//Failed when tested with a path...need to change the current working directory???


hSearch = FindFirstFile(L"C:\\*.txt", &FileData);



printf("No .txt files found lol.\n");

//just exit

exit (0);



//Copy each .txt file to the new directory and change it to read only, if any...


{ //Copies a string in szDirPath to szNewPath buffer...

lstrcpy(szNewPath, szDirPath);


//Appends the filename to the path...

lstrcat(szNewPath, FileData.cFileName);

printf("szNewPath is %S\n", szNewPath);


//In the buffer, do the file copy...

if(CopyFile(FileData.cFileName, szNewPath, FALSE))


printf("%S file successfully copied.\n", FileData.cFileName);

//And gets the file attribute...

dwAttrs = GetFileAttributes(FileData.cFileName);

//Change to read only where applicable...


SetFileAttributes(szNewPath, dwAttrs | FILE_ATTRIBUTE_READONLY);



printf("Could not copy %S file. Error code: %d\n", FileData.cFileName, GetLastError());

if(!FindNextFile(hSearch, &FileData))


if(GetLastError() == ERROR_NO_MORE_FILES)


printf("No more file lol!\n");

fFinished = TRUE;



printf("Could not find next file.\n");



//Close the search handle.


return 0;



Output example:


E:\newdir\ directory successfully created.

szNewPath is E:\newdir\data.txt

Could not copy data.txt file. Error code: 2

szNewPath is E:\newdir\mytestfile.txt

Could not copy mytestfile.txt file. Error code: 2

szNewPath is E:\newdir\original.txt

Could not copy original.txt file. Error code: 2

szNewPath is E:\newdir\YServer.txt

Could not copy YServer.txt file. Error code: 2

No more file lol!

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index