日付付きのログ出力関数を作ります。
◆環境
OS |
Windows 7 Professional Service Pack 1 64bit |
VC |
Microsoft Visual C++ 2005 77972-235-2482122-41280 |
[ファイル]-[新規作成]-[プロジェクト]を選択します。
「プロジェクトの種類」欄で[Visual C++]-[Win32]を選択し、[Win32 コンソール アプリケーション]を選択します。
「プロジェクト名」は「OutputLogTest」にします。
ウィザードが起動したら、「完了」を押します。
時刻の取得は GetLocalTime関数を使いました。
OutputLogTest.cpp
|
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
|
// OutputLogTest.cpp : コンソール アプリケーションのエントリ
// ポイントを定義します。
//
#include "stdafx.h"
#include "windows.h"
int OutputLog ( const char* format, ... );
int _tmain( int argc, _TCHAR* argv[] )
{
OutputLog( "OutputLogTest START" );
Sleep( 1000 );
OutputLog( "OutputLogTest END" );
return 0;
}
//===============================================================
// [関数名] OutputLog
//
// [概 要] 実行ファイルを同じフォルダにログを出力する。
//
// [引 数] const char* format ログ内容(255文字まで)
//
// [戻り値] 0:成功
// -1:ログファイルOpen失敗
//===============================================================
int OutputLog( const char* format, ... )
{
FILE* fp = NULL;
fopen_s( &fp, "OutputLog.log", "a" );
if ( fp == NULL )
{
return -1;
}
// 現在のローカル時刻を取得
SYSTEMTIME st;
GetLocalTime( &st );
char buf[255+1];
va_list ap;
va_start( ap, format );
vsprintf_s( buf, sizeof( buf ), format, ap );
va_end( ap );
fprintf( fp
, "%04d/%02d/%02d %02d:%02d:%02d.%03d %s\n"
, st.wYear
, st.wMonth
, st.wDay
, st.wHour
, st.wMinute
, st.wSecond
, st.wMilliseconds
, buf
);
fclose( fp );
return 0;
}
|
|
実行すると見た目は何も起こりませんが、OutputLog.logファイルが作られました。
内容は以下でした。
2014/07/15 10:08:36.417 OutputLogTest START
2014/07/15 10:08:37.431 OutputLogTest END
いいですね。
▲ PageTop ■ Home
Copyright (C) 2014 ymlib.com