5.2.4 Example: Searching for Files and Changing File Attributes

The following code fragment copies all text files in the current directory to a new directory named \TEXTRO. All files in the new directory are changed to read-only, if they are not already.

The application uses the GetCurrentDirectory function to save the current directory path. This will be used to return to the current directory after changing to the \TEXTRO directory.

The application then creates the \TEXTRO directory by using the CreateDirectory function.

The application then searches the current directory for all *.TXT files by using the FindFirstFile and FindNextFile functions. Each *.TXT file is copied to the \TEXTRO directory. After a file is copied, the GetFileAttributes function determines if the file is read-only. If the file is not read-only, the application changes to the \TEXTRO directory and changes the copied file to read-only by using the SetFileAttributes function.

After all the *.TXT files in the current directory have been copied, the application closes the search handle with the FindClose function.

WIN32_FIND_DATA FileData;

HANDLE hSearch;

DWORD dwAttrs;

char szDirPath[] = "c:\\TextRO\\";

char szNewPath[MAX_PATH];

char szHome[MAX_PATH];

BOOL fFinished = FALSE;

/* Create new directory. */

if (!CreateDirectory(szDirPath, NULL)) {

ErrorHandler("Couldn't create new directory.");

}

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

hSearch = FindFirstFile("*.txt", &FileData);

if (hSearch == INVALID_HANDLE_VALUE) {

ErrorHandler("No .txt files found.");

}

/*

* Copy each .txt file to the new directory

* and change to read-only, if not already.

*/

while (!fFinished) {

lstrcpy(szNewPath, szDirPath);

lstrcat(szNewPath, FileData.cFileName);

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

dwAttrs = GetFileAttributes(FileData.cFileName);

if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) {

SetFileAttributes(szNewPath,

dwAttrs | FILE_ATTRIBUTE_READONLY);

}

}

else {

ErrorHandler("Couldn't copy file.");

}

if (!FindNextFile(hSearch, &FileData))

if (GetLastError() == ERROR_NO_MORE_FILES) {

MessageBox(hwnd, "No more .txt files.",

"Search completed.", MB_OK);

fFinished = TRUE;

}

else {

ErrorHandler("Couldn't find next file.");

}

}

/* Close search handle. */

if (!FindClose(hSearch)) {

ErrorHandler("Couldn't close search handle.");

}