[CMD]: Improvements for the CHCP command.
[reactos.git] / reactos / base / shell / cmd / chcp.c
1 /*
2 * CHCP.C - chcp internal command.
3 *
4 *
5 * History:
6 *
7 * 23-Dec-1998 (Eric Kohl)
8 * Started.
9 *
10 * 02-Apr-2005 (Magnus Olsen <magnus@greatlord.com>)
11 * Remove all hardcoded strings in En.rc
12 */
13
14 #include "precomp.h"
15
16 #ifdef INCLUDE_CMD_CHCP
17
18 INT CommandChcp(LPTSTR param)
19 {
20 LPTSTR *arg;
21 INT args;
22 UINT uNewCodePage;
23
24 /* Print help */
25 if (!_tcsncmp(param, _T("/?"), 2))
26 {
27 ConOutResPaging(TRUE,STRING_CHCP_HELP);
28 return 0;
29 }
30
31 nErrorLevel = 0;
32
33 /* Get parameters */
34 arg = split(param, &args, FALSE, FALSE);
35
36 if (args == 0)
37 {
38 /* Display the active code page number */
39 ConOutResPrintf(STRING_CHCP_ERROR1, OutputCodePage);
40 freep(arg);
41 return 0;
42 }
43
44 if (args >= 2)
45 {
46 /* Too many parameters */
47 ConErrResPrintf(STRING_ERROR_INVALID_PARAM_FORMAT, param);
48 freep(arg);
49 nErrorLevel = 1;
50 return 1;
51 }
52
53 uNewCodePage = (UINT)_ttoi(arg[0]);
54
55 if (uNewCodePage == 0)
56 {
57 ConErrResPrintf(STRING_ERROR_INVALID_PARAM_FORMAT, arg[0]);
58 freep(arg);
59 nErrorLevel = 1;
60 return 1;
61 }
62
63 freep(arg);
64
65 // TODO: In case of failure of SetConsoleCP or SetConsoleOutputCP,
66 // restore the old code page!
67
68 /*
69 * Try changing the console input codepage. If it works then also change
70 * the console output codepage, and refresh our local codepage cache.
71 */
72 if (!SetConsoleCP(uNewCodePage))
73 {
74 ConErrResPuts(STRING_CHCP_ERROR4);
75 }
76 else
77 {
78 SetConsoleOutputCP(uNewCodePage);
79
80 /* Update our local codepage cache */
81 InputCodePage = GetConsoleCP();
82 OutputCodePage = GetConsoleOutputCP();
83
84 InitLocale();
85
86 /* Display the active code page number */
87 ConOutResPrintf(STRING_CHCP_ERROR1, OutputCodePage);
88 }
89
90 return 0;
91 }
92
93 #endif /* INCLUDE_CMD_CHCP */