回答編集履歴

2

表示結果部分の修正

2017/05/21 05:33

投稿

退会済みユーザー
test CHANGED
@@ -150,21 +150,13 @@
150
150
 
151
151
  Hello, World! => コマンドプロンプトに表示される
152
152
 
153
-
154
-
155
153
  >main.exe > hello.txt => hello.txtにリダイレクト
156
154
 
157
155
  => コマンドプロンプトには表示されない
158
156
 
157
+ >type hello.txt => hello.txtの中身をコマンドプロンプトに表示
159
158
 
160
-
161
- ```
162
-
163
-
164
-
165
- ```
166
-
167
- Hello, World! => hello.txtの中身
159
+ Hello, World!
168
160
 
169
161
  ```
170
162
 

1

新しいコードの追加

2017/05/21 05:33

投稿

退会済みユーザー
test CHANGED
@@ -67,3 +67,109 @@
67
67
 
68
68
 
69
69
  ※VC++の場合、`freopen_s`では無く`freopen`を使わないと`FreeConsole`で例外が発生して停止します。
70
+
71
+
72
+
73
+ ---
74
+
75
+
76
+
77
+ 色々と調べた結果の修正版
78
+
79
+
80
+
81
+ ```cpp
82
+
83
+ #include <windows.h>
84
+
85
+ #include <tchar.h>
86
+
87
+ #include <io.h>
88
+
89
+ #include <fcntl.h>
90
+
91
+ #include <stdio.h>
92
+
93
+
94
+
95
+ int APIENTRY _tWinMain(HINSTANCE, HINSTANCE, LPTSTR lpCmdLine, int)
96
+
97
+ {
98
+
99
+ if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
100
+
101
+ AllocConsole();
102
+
103
+ }
104
+
105
+
106
+
107
+ HANDLE hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
108
+
109
+ int fd = _open_osfhandle((intptr_t)hConOut, _O_TEXT );
110
+
111
+ *stdout = *_fdopen(fd, "w");
112
+
113
+ setvbuf(stdout, nullptr, _IONBF, 0);
114
+
115
+
116
+
117
+ printf("Hello, World!\n");
118
+
119
+
120
+
121
+ Sleep(2000);
122
+
123
+
124
+
125
+ _close(fd);
126
+
127
+ FreeConsole();
128
+
129
+
130
+
131
+ return 0;
132
+
133
+ }
134
+
135
+ ```
136
+
137
+
138
+
139
+ 実行結果:
140
+
141
+
142
+
143
+ ```
144
+
145
+ >g++ main.cpp -mwindows -o main.exe => subsystemをGUIにしてビルド
146
+
147
+
148
+
149
+ >main.exe => ファイルにリダイレクトせずに実行
150
+
151
+ Hello, World! => コマンドプロンプトに表示される
152
+
153
+
154
+
155
+ >main.exe > hello.txt => hello.txtにリダイレクト
156
+
157
+ => コマンドプロンプトには表示されない
158
+
159
+
160
+
161
+ ```
162
+
163
+
164
+
165
+ ```
166
+
167
+ Hello, World! => hello.txtの中身
168
+
169
+ ```
170
+
171
+
172
+
173
+ `freopen_s`を使用した最初の方法ではファイルにリダイレクトしても何も書き込まれませんでしたが、今回のはちゃんと書き込まれました。
174
+
175
+ これでいかがでしょう?