// GetFileAttributes 获取文件的属性。此例子代码摘自MSDN,把程序目录下面的txt格式文件复制到新建的文件夹下,并且修改这些文件的属性为只读。
// 用到的API:CreateDirectory、FindFirstFile、FindNextFile、FindClose、GetFileAttributes、SetFileAttributes、CopyFile。
1 #include <Windows.h>
2 #include <stdio.h>
3 #include <strsafe.h>
4
5 void main()
6 {
7 WIN32_FIND_DATA FileData;
8 HANDLE hSearch;
9 DWORD dwAttrs;
10 TCHAR szDirPath[] = TEXT("c:\\TextRO\\");
11 TCHAR szNewPath[MAX_PATH];
12
13 BOOL fFinished = FALSE;
14
15 // Create a new directory.
16
17 if (!CreateDirectory(szDirPath, NULL))
18 {
19 printf("Could not create new directory.\n");
20 return;
21 }
22
23 // Start searching for text files in the current directory.
24
25 hSearch = FindFirstFile(TEXT("*.txt"), &FileData);
26 if (hSearch == INVALID_HANDLE_VALUE)
27 {
28 printf("No text files found.\n");
29 return;
30 }
31
32 // Copy each .TXT file to the new directory
33 // and change it to read only, if not already.
34
35 while (!fFinished)
36 {
37 StringCchCopy(szNewPath, MAX_PATH, szDirPath);
38 StringCchCat(szNewPath, MAX_PATH, FileData.cFileName);
39 if (CopyFile(FileData.cFileName, szNewPath, FALSE))
40 {
41 dwAttrs = GetFileAttributes(FileData.cFileName);
42 if (dwAttrs==INVALID_FILE_ATTRIBUTES) return;
43
44 if (!(dwAttrs & FILE_ATTRIBUTE_READONLY))
45 {
46 SetFileAttributes(szNewPath,
47 dwAttrs | FILE_ATTRIBUTE_READONLY);
48 }
49 }
50 else
51 {
52 printf("Could not copy file.\n");
53 return;
54 }
55
56 if (!FindNextFile(hSearch, &FileData))
57 {
58 if (GetLastError() == ERROR_NO_MORE_FILES)
59 {
60 printf("Copied all text files.\n");
61 fFinished = TRUE;
62 }
63 else
64 {
65 printf("Could not find next file.\n");
66 return;
67 }
68 }
69 }
70
71 // Close the search handle.
72
73 FindClose(hSearch);
74 }
posted on 2010-03-01 21:15
郭小帅 阅读(1443)
评论(0) 编辑 收藏 引用 所属分类:
API