[FSUTIL]
[reactos.git] / reactos / base / applications / cmdutils / fsutil / common.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS FS utility tool
4 * FILE: base/applications/cmdutils/common.c
5 * PURPOSE: FSutil common functions
6 * PROGRAMMERS: Pierre Schweitzer <pierre@reactos.org>
7 */
8
9 #include "fsutil.h"
10
11 int FindHandler(int argc,
12 const TCHAR *argv[],
13 HandlerItem * HandlersList,
14 int HandlerListCount,
15 void (*UsageHelper)(const TCHAR *))
16 {
17 int i;
18 int ret;
19 const TCHAR * Command;
20
21 ret = 1;
22 Command = NULL;
23 i = HandlerListCount;
24
25 /* If we have a command, does it match a known one? */
26 if (argc > 1)
27 {
28 /* Browse all the known commands finding the right one */
29 Command = argv[1];
30 for (i = 0; i < HandlerListCount; ++i)
31 {
32 if (_tcsicmp(Command, HandlersList[i].Command) == 0)
33 {
34 ret = HandlersList[i].Handler(argc - 1, &argv[1]);
35 break;
36 }
37 }
38 }
39
40 /* We failed finding someone to handle the caller's needs, print out */
41 if (i == HandlerListCount)
42 {
43 UsageHelper(Command);
44 }
45
46 return ret;
47 }
48
49 HANDLE OpenVolume(const TCHAR * Volume,
50 BOOLEAN AllowRemote)
51 {
52 UINT Type;
53 HANDLE hVolume;
54 TCHAR VolumeID[PATH_MAX];
55
56 /* Create full name */
57 _stprintf(VolumeID, _T("\\\\.\\%s"), Volume);
58
59 /* Get volume type */
60 if (!AllowRemote && Volume[1] == L':')
61 {
62 Type = GetDriveType(Volume);
63 if (Type == DRIVE_REMOTE)
64 {
65 _ftprintf(stderr, _T("FSUTIL needs a local device\n"));
66 return INVALID_HANDLE_VALUE;
67 }
68 }
69
70 /* Open the volume */
71 hVolume = CreateFile(VolumeID, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
72 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
73 if (hVolume == INVALID_HANDLE_VALUE)
74 {
75 PrintErrorMessage(GetLastError());
76 return INVALID_HANDLE_VALUE;
77 }
78
79 return hVolume;
80 }
81
82 void PrintDefaultUsage(const TCHAR * Command,
83 const TCHAR * SubCommand,
84 HandlerItem * HandlersList,
85 int HandlerListCount)
86 {
87 int i;
88
89 /* If we were given a command, print it's not supported */
90 if (SubCommand != NULL)
91 {
92 _ftprintf(stderr, _T("Unhandled%scommand: %s\n"), Command, SubCommand);
93 }
94
95 /* And dump any available command */
96 _ftprintf(stderr, _T("---- Handled%scommands ----\n\n"), Command);
97 for (i = 0; i < HandlerListCount; ++i)
98 {
99 _ftprintf(stderr, _T("%s\t%s\n"), HandlersList[i].Command, HandlersList[i].Desc);
100 }
101 }
102
103 int PrintErrorMessage(DWORD Error)
104 {
105 TCHAR * String;
106
107 /* Try to get textual error */
108 if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
109 NULL, Error, 0, (TCHAR *)&String, 0, NULL) != 0)
110 {
111 /* And print it */
112 _ftprintf(stderr, _T("Error: %s\n"), String);
113 LocalFree(String);
114 }
115 else
116 {
117 /* Otherwise, just print the error number */
118 _ftprintf(stderr, _T("Error: %d\n"), Error);
119 }
120
121 return Error;
122 }