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)
{
WIN32_FIND_DATA FileData;
HANDLE hSearch;
DWORD dwAttrs;
//LPCWSTR szDirPath = L"E:\\newdir\\";
//LPWSTR szNewPath = malloc(sizeof(MAX_PATH));
TCHAR szDirPath[] = TEXT("E:\\newdir\\");
TCHAR szNewPath[MAX_PATH];
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);
}
else
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);
if(hSearch == INVALID_HANDLE_VALUE)
{
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...
while(!fFinished)
{ //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...
if(!(dwAttrs & FILE_ATTRIBUTE_READONLY))
SetFileAttributes(szNewPath, dwAttrs | FILE_ATTRIBUTE_READONLY);
}
else
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;
}
else
printf("Could not find next file.\n");
}
}
//Close the search handle.
FindClose(hSearch);
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 . . .